LeetCode Problem: Maximum Depth of Binary Tree

By | 2013 年 1 月 19 日

Recursively count the depth of tree node. One node’s depth is the maximum depth of it’s children’s depth + 1 or 0 if node is NULL.
递归计算就可以了,如果是空节点,深度是0,否则这个节点的子树的最大深度是其子节点最大深度 + 1。



Maximum Depth of Binary Tree Sep 30 ’12
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.



Code, 64ms pass large set

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(root == NULL) return 0;
        int leftdep = maxDepth(root->left);
        int rightdep = maxDepth(root->right);
        return 1 + std::max(leftdep,rightdep);
    }
};

发表评论

电子邮件地址不会被公开。 必填项已用*标注