問題描述:
給定一個二叉樹,找出其最大深度。
二叉樹的深度爲根節點到最遠葉子節點的距離。
樣例
給出一棵如下的二叉樹:
1
/ \
2 3
/ \
4 5
這個二叉樹的最大深度爲3
.
解題思路:
運用遞歸的方法,分別得到左、右子樹根的數目,再加上二叉樹的根節點,經過比較,得到該樹的最大深度
代碼:
/**
* 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
*/
int maxDepth(TreeNode *root) {
if(root==NULL) return 0;
else{
int p=maxDepth(root->left)+1;
int q=maxDepth(root->right)+1;
if(p>q)return p;
else return q;
} // write your code here
}
};
* 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
*/
int maxDepth(TreeNode *root) {
if(root==NULL) return 0;
else{
int p=maxDepth(root->left)+1;
int q=maxDepth(root->right)+1;
if(p>q)return p;
else return q;
} // write your code here
}
};
感想:
要了解遞歸的過程並能夠合理應用