1. 程式人生 > >劍指offer三十八之二叉樹的深度

劍指offer三十八之二叉樹的深度

ret terminal pro roo 結點 路徑 splay close solution

一、題目

  輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度為樹的深度。

二、思路

  遞歸,詳見代碼。

三、代碼

技術分享
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

劍指offer三十八之二叉樹的深度