LeetCode Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.


计算出二叉树的最大深度,简单题,直接深搜即可。。。 完整代码如下:

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


本代码提交AC,用时13MS。
二刷。还可以更简洁一些:

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

本代码提交AC,用时6MS。

2 thoughts on “LeetCode Maximum Depth of Binary Tree

  1. Pingback: LeetCode Minimum Depth of Binary Tree | bitJoy > code

  2. Pingback: LeetCode Print Binary Tree | bitJoy > code

Leave a Reply

Your email address will not be published. Required fields are marked *