描述:給定一個二叉樹,找出其最大深度。
二叉樹的深度爲根節點到最遠葉子節點的距離。
樣例
給出一棵如下的二叉樹:
思路:想到要採用遞歸調用的方法,但是不知道從何下手。後面參考網上,對左右子樹都進行Max函數的調用,然後進行比較,較大者即爲深度減1的量。
/**
* 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) {
// write your code here
if(root == NULL) return 0;
int left=maxDepth(root->left);
int right=maxDepth(root->right);
return max(left,right)+1;
}
};
拓展:有最大深度,自然而然有最小深度。
思路:同樣採用遞歸調用。只是有一點不同:因爲深度是必須到葉子節點的距離,因此使用深度遍歷時,不能單純的比較左右子樹的遞歸結果返回較小值,因爲對於有單個孩子爲空的節點,爲空的孩子會返回0,但這個節點並非葉子節點,故返回的結果是錯誤的。因此,當發現當前處理的節點有單個孩子是空時,返回一個極大值INT_MAX,防止其干擾結果。
class Solution {
public:
int minDepth(TreeNode *root) {
if(!root) return 0;
if(!root -> left && !root -> right) return 1; //Leaf means should return depth.
int leftDepth = minDepth(root -> left);
leftDepth = (leftDepth == 1 ? INT_MAX : leftDepth);
int rightDepth = minDepth(root -> right);
rightDepth = (rightDepth == 1 ? INT_MAX : rightDepth); //If only one child returns 1, means this is not leaf, it does not return depth.
return min(leftDepth, rightDepth)+1;
}
};