LeetCode104 給定一個二叉樹,找出其最大深度。 二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。 說明: 葉子節點是指沒有子節點的節點。
阿新 • • 發佈:2019-02-19
給定一個二叉樹,找出其最大深度。
二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。
說明: 葉子節點是指沒有子節點的節點。
/**
* 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)
{
return 0;
}
if(!root->left&&root->right)
{
return maxDepth(root->right)+1;
}
if(root->left&&!root->right)
{
return maxDepth(root->left)+1;
}
if(!root->left &&!root->right)
{
return 1;
}
return max(maxDepth(root->left),maxDepth(root->right))+1;
}
};