Maximum Depth of Binary Tree

LeetCode #104


Description:

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.

If one Node, depth = 1; If null Node, depth = 0.

Example:

Note

Idea:

容易,直接从left subtree and right subtree里找depth最大的就行。即便一边的subtree是null,那么那边depth就是0+1,因为两边取max(),所以不影响,这点不像minDepth。

Code:

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root==NULL) return 0;

        int left_depth=maxDepth(root->left);
        int right_depth=maxDepth(root->right);

        return max(left_depth, right_depth) + 1;
    }
};

results matching ""

    No results matching ""