二叉树的深度

给定一个二叉树,求二叉树的深度,即从跟节点到叶节点的最长路径。
若只有一个顶点,则深度为1,若二叉树为空则返回0。
输入、输出描述
输入:
给定一个二叉树的根节点
输出:
二叉树的深度
Example
输入:
二叉树如下:
    1
   / \
   2  3
  /
  4
   \
    5
输出:
4
代码:
import java.util.*;

public class Main {

    public int solution(TreeNode<Integer> root) {
        if (root == null) {
            return 0;
        } else if (root.left == null && root.right == null) {
            return 1;
        }

        int left = 0;
        int right = 0;

        if (root.left != null) {
            left = solution(root.left);
        }

        if (root.right != null) {
            right = solution(root.right);
        }

        return Math.max(left + 1, right + 1);

    }

}
一个创业中的苦逼程序员
评论专区

隐藏