剑指Offer:二叉树的深度 (java代码实现)

题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
递归思路
求左子树的高度 lh
求右子树的高度 rh
选取2个高度中高的那个加上1 就是当前结点的高度

下面代码实现

public class Solution {
    public int TreeDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }
        return Math.max(TreeDepth(root.left) + 1, TreeDepth(root.right) + 1);
    }
}

猜你喜欢

转载自blog.csdn.net/wmh1152151276/article/details/88078308