https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

https://leetcode.com/problems/maximum-depth-of-binary-tree/

递归。计算左子树高度和右子树高度的较大者。记得+1。

执行用时: c++ 4ms; java 1ms; python 68ms

 

c++

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root==NULL)
            return 0;
        return max(maxDepth(root->left),maxDepth(root->right))+1;
    }
};

java

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

python

class Solution:
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root is None:
            return 0
        return max(self.maxDepth(root.left),self.maxDepth(root.right))+1