描述:给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的距离。
样例
给出一棵如下的二叉树:
思路:想到要采用递归调用的方法,但是不知道从何下手。后面参考网上,对左右子树都进行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;
}
};