跳转至

104.Maximum Depth of Binary Tree

Tags: Easy Tree Depth-first Search

Links: https://leetcode.com/problems/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.


/**
 * 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) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        if (!root) return 0;
        return 1 + max(maxDepth(root -> left), maxDepth(root -> right));
    }
};
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Maximum Depth of Binary Tree.
Memory Usage: 18.4 MB, less than 100.00% 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) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        if (!root) return 0;
        int res = 0;
        queue<TreeNode *> q;
        q.push(root);
        while (!q.empty()) {
            int len = q.size();
            ++res;
            for (int i = 0; i < len; ++i) {
                TreeNode *tmp = q.front(); q.pop();
                if (tmp -> left) q.push(tmp -> left);
                if (tmp -> right) q.push(tmp -> right);
            }
        }
        return res;
    }
};
Runtime: 4 ms, faster than 98.68% of C++ online submissions for Maximum Depth of Binary Tree.
Memory Usage: 18.4 MB, less than 100.00% of C++ online submissions for Maximum Depth of Binary Tree.

利用层序遍历的方法。