剑指offer三十八之二叉树的深度

一、题目

  输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

二、思路

  递归,详见代码。

三、代码

public class Solution {
 public int TreeDepth(TreeNode pRoot)
    {
     if(pRoot == null)
            return 0;
        if(pRoot.left == null && pRoot.right == null)
            return 1;
        int left = TreeDepth(pRoot.left);
        int right = TreeDepth(pRoot.right);
        
        return left > right ? left + 1 : right + 1;
    }
}
View Code

---------------------------------------------

参考链接:

https://www.nowcoder.com/questionTerminal/435fb86331474282a3499955f0a41e8b

原文地址:https://www.cnblogs.com/hezhiyao/p/7656457.html