二叉树的深度

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

我的代码:

class Solution {
    int depth = 0;
    int con = 0;
public:
    int TreeDepth(TreeNode* pRoot)
    {
        if(!pRoot)
            return con;
        depth++;
        if(pRoot->left == NULL && pRoot->right == NULL )
        {
            if(depth > con)
                con = depth;
            return con;
        }
        if(pRoot->left)
        {
            TreeDepth(pRoot->left);
            depth--;
        }
        if(pRoot->right)
        {
            TreeDepth(pRoot->right);
            depth--;
        }
        return con;
    }
};

哇塞塞!别人的代码

class Solution {
public:
    int TreeDepth(TreeNode* pRoot){
        if(!pRoot) return 0 ;
            return max(1+TreeDepth(pRoot->left), 1+TreeDepth(pRoot->right));
    }
};

还有:

import java.lang.Math;
public class Solution {
    public int TreeDepth(TreeNode pRoot)
    {
        if(pRoot == null){
            return 0;
        }
        int left = TreeDepth(pRoot.left);
        int right = TreeDepth(pRoot.right);
        return Math.max(left, right) + 1;
    }
}
原文地址:https://www.cnblogs.com/Lune-Qiu/p/8778582.html