LeetCode104:Maximum Depth of Binary Tree

736 ワード

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.
Show Tags
Show Similar Problems
二叉木の深さを計算するには、再帰的な解を用いることが非常に容易であり、1つのノードの深さはその左のサブツリーの深さとその右のサブツリーの深さの最大値に1を加え、空のツリーの深さは0である.
/**
 * 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;
            
        return max(maxDepth(root->left),maxDepth(root->right))+1;
    }
};