您的位置:首页 > 其它

【对递归的理解】Maximum Depth of Binary Tree

2015-03-23 15:49 561 查看
【题目描述】

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.

求一棵二叉树的最大深度,利用递归实现。代码如下:

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode *root) {
if(root == NULL){
return 0;
}
int leftMax = maxDepth(root->left);
int rightMax = maxDepth(root->right);
if(leftMax >= rightMax){
return leftMax+1;
}
else{
return rightMax+1;
}
}
};
递归程序调用过程分析如下:

以一个非常简单的二叉树作为示例,第一次进入递归函数时,用单箭头表示。返回时用双箭头表示并用ret加上返回值返回。具体调用过程见下图:



总结:

1. 要有能使递归终止的条件,否则将一直执行下去;

2.每一层次的递归函数调用都会有本层次递归函数的局部变量,再遇到返回条件时反方向向前返回值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: