您的位置:首页 > 其它

【38】二叉树的深度

2016-08-05 11:53 113 查看

[38]二叉树的深度

时间限制:1秒

空间限制:32768K

题目描述

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

题目链接点击这里

VS2010代码

// Source : http://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b?tpId=13&tqId=11191&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking // Author : Qiang Yang
// Date   : 2016-08-04

/**************************************************************
*
*[38]二叉树的深度
*参与人数:4679
*时间限制:1秒
*空间限制:32768K
*
*题目描述
*
*输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点
*(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
*
****************************************************************/

#include<iostream>
#include<vector>
using namespace std;

//思路:
//设置两个参数,当前最大深入和候选深度。用深度优先遍历整个树。
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if(!pRoot) return 0;
int LDepth=0;   //左支深度
int RDepth=0;   //右支深度
int Depth=1;    //当前最大深度
//当前左支深度
LDepth=Depth+TreeDepth(pRoot->left);

//当前右支深度
RDepth=Depth+TreeDepth(pRoot->right);

//由左右支深度更新当前最大深度
LDepth<RDepth? Depth=RDepth:Depth=LDepth;

return Depth;
}
};

//测试用例:
//1.{1,2,3,4,5,#,6,#,#,7},对应输出 4 。


说明:感觉这是代码写的最少的一次。深入理解递归。

从顶层向下思考,从底层向上执行。

牛客网通过图片:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树 深度 递归