給定一個二叉樹,找出其最大深度。
二叉樹的深度為根節點到最遠葉子節點的距離。
樣例
給出一棵如下的二叉樹:
1/ \
2 3/ \4 5
這個二叉樹的最大深度為3
.
?
二叉樹最小深度公式、思路:與二叉樹最小深度思路一樣,一次AC;
??????
????? 這種容易題目要很熟練,主要是思路要清晰。
?
/*** Definition of TreeNode:* class TreeNode {* public:* int val;* TreeNode *left, *right;* TreeNode(int val) {* this->val = val;* this->left = this->right = NULL;* }* }*/
class Solution {
public:/*** @param root: The root of binary tree.* @return: An integer*//*思路:與二叉樹最小深度思路一樣,一次AC;這種容易題目要很熟練。*/int maxDepth(TreeNode *root) {// write your code hereif(root==NULL){return 0;}if(root->left==NULL){return maxDepth(root->right)+1;}if(root->right==NULL){return maxDepth(root->left)+1;}return max(maxDepth(root->left),maxDepth(root->right))+1;}
};
?