首页 > 其他 > 详细

二叉树的深度

时间:2018-01-31 17:48:55      阅读:243      评论:0      收藏:0      [点我收藏+]

题目描述

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
 
思路:基于深度优先遍历求二叉树深度
 1 /*
 2 struct TreeNode {
 3     int val;
 4     struct TreeNode *left;
 5     struct TreeNode *right;
 6     TreeNode(int x) :
 7             val(x), left(NULL), right(NULL) {
 8     }
 9 };*/
10 class Solution {
11 public:
12     void DFS(TreeNode *pRoot, int &maxDeepth, int curDeepth)
13     {
14         ++curDeepth;
15         if(pRoot->left)DFS(pRoot->left, maxDeepth, curDeepth);
16         if(pRoot->right)DFS(pRoot->right, maxDeepth, curDeepth);
17         if(curDeepth>maxDeepth)maxDeepth=curDeepth;
18     }
19     int TreeDepth(TreeNode* pRoot)
20     {
21         if(pRoot==NULL)return 0;
22         int maxDeepth=0;
23         int curDeepth=0;
24         DFS(pRoot, maxDeepth, curDeepth);
25         return maxDeepth;
26     }
27 };

 

二叉树的深度

原文:https://www.cnblogs.com/jeysin/p/8393336.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!