问题描述:
给定一个二叉树,找其最大深度。二叉树的深度为根节点到最远叶子节点的距离。
实现思路:
求出左子树和右子树的深度,得出最大值,返回最大值加一(因为还有根节点)。考虑斜树。
实现代码:
/**
* 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;
if(root!=NULL) {
if(root->left==NULL) return maxDepth(root->right)+1;
if(root->right==NULL) return maxDepth(root->left)+1;
int rightDepth=maxDepth(root->right);
int leftDepth=maxDepth(root->left);
return leftDepth>rightDepth?(leftDepth+1):(rightDepth+1);
}
}
};
感想:
利用递归求得左子树和右子树的深度的最大值,还要考虑斜树的情况。