Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Hide Tags: Tree ,Depth-first Search
题目:求取二叉树中最大深度,根节点定义为1深度。
思路:同样采取递归
递归终止条件:
A:如果root为NULL,说明已经越界,返回深度0
判断节点走向:
A:如果root为树叶, if(root->left == NULL && root->right == NULL) 返回深度1
B:如果节点无左节点,即if(root->left == NULL ) ,则执行递归return minDepth(root->right) + 1;
C:如果节点无右节点,则return minDepth(root->left ) + 1;
递归主进程:
int l = minDepth(root->left) + 1 ;
int r = minDepth(root->right)+ 1 ;
最后在判断l与r的大小,返回大者 return l>r ? l : r ;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode* root) {
if(root == NULL) return 0;
if(root->left == NULL && root->right == NULL) return 1;
else if(root->left == NULL) return maxDepth(root->right) + 1;
else if(root->right== NULL) return maxDepth(root->left ) + 1;
int l = maxDepth(root->left) + 1;
int r = maxDepth(root->right)+ 1;
return l>r?l:r;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
[leetcode]-Maximum Depth of Binary Tree
原文地址:http://blog.csdn.net/xiabodan/article/details/46771205