剑指offer 二叉树的深度

本文介绍了两种求解二叉树深度的方法:递归法和层次遍历法。递归法通过比较左右子树深度并加一得到结果,而层次遍历法则利用队列进行逐层节点计数。

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

 

分析:恩。。没啥好分析的,很基础的一题,有多种解法,如递归,层次遍历。

 

解法一:递归

树的深度=max(左子树的深度, 右子树的深度)+ 节点本身的深度(为1)

递归终止条件:如果节点本身为NULL,则返回深度为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     int TreeDepth(TreeNode* pRoot)
13     {
14         if (pRoot == NULL) {
15             return 0;
16         }
17         int left = TreeDepth(pRoot->left);
18         int right = TreeDepth(pRoot->right);
19         return max(left, right) + 1;
20     }
21 };

解法二:层次遍历

 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     int TreeDepth(TreeNode* pRoot)
13     {
14         queue<TreeNode*> que;
15         int depth = 0;
16         if (pRoot == NULL) {
17             return 0;
18         }
19         que.push(pRoot);
20         while(!que.empty()) {
21             int len = que.size();
22             depth++;
23             for (int i = 0; i < len; i++) {
24                 TreeNode *tmp = que.front();
25                 que.pop();
26                 if (tmp->left != NULL) {
27                     que.push(tmp->left);
28                 }
29                 if (tmp->right != NULL) {
30                     que.push(tmp->right);
31                 }
32             }
33         }
34         return depth;
35     }
36 };

 

转载于:https://www.cnblogs.com/qinduanyinghua/p/10474322.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值