MENU

LeetCode104. Maximum Depth of Binary Tree(二叉树 / 搜索)

2019 年 03 月 07 日 • 阅读: 1020 • LeetCode阅读设置

LeetCode104. Maximum Depth of Binary Tree(二叉树 / 搜索)

  • Easy
  • Accepted:458,799
  • Submissions:774,287

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.


链接

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

题意

给定一棵二叉树,求它的最大深度。即从根节点到叶子节点的最长路径长度。

题解

递归的搜索左子树的深度l1,右子树的深度l2,那么对于当前结点的最大深度就是max(l1, l2) + 1。时间复杂度的话考虑一颗满二叉树,$T(n) = 2T(n/2)+ 1, T(1) = 1$,为$O(n)$。

代码

  • Runtime: 16 ms, faster than 99.26% of C++ online submissions for Maximum Depth of Binary Tree.
  • Memory Usage: 19.6 MB, less than 12.18% of C++ online submissions for Maximum Depth of Binary Tree.
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

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

// simple
class Solution {
public:
    int maxDepth(TreeNode* root) {
        return root == NULL ? 0 : max(maxDepth(root->left), maxDepth(root->right)) + 1;
    }
};
  • 当然我们也可以使用队列,即bfs。
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == NULL)
            return 0;
        int ans = 0;
        queue <TreeNode*> q;
        q.push(root);
        while (!q.empty())
        {
            ++ans;
            int n = q.size();
            for (int i = 0; i < n; ++i)
            {
                TreeNode* p = q.front();
                q.pop();
                if (p->left != NULL)
                    q.push(p->left);
                if (p->right != NULL)
                    q.push(p->right);
            }            
        }
        return ans;
    }
};

参考

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


The end.
2019年3月7日 星期四