zerofly's Blog

努力不一定成功,但不努力一定不会成功

0%

二叉树的深度


题目描述

输入一颗二叉树,求该树的深度。

解题思路

求二叉树深度,通常有两种做法。

  • 一种是通过深度优先遍历得到二叉树的深度;
  • 另一种是通过广度优先遍历(层次遍历)得到二叉树的深度;

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 深度优先遍历
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 == NULL)
return 0;

int left = TreeDepth(pRoot->left);
int right = TreeDepth(pRoot->right);

return (left > right) ? (left + 1) : (right + 1);
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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 == NULL)
return 0;

queue<TreeNode*> Q;

Q.push(pRoot);
int depth = 0;

while (!Q.empty())
{
int size = Q.size();
depth++;
for (int i = 0; i < size; i++) // 把每层的结点依次删除,然后存入下一层所有结点
{
TreeNode* temp = Q.front();
Q.pop();
if (temp->left)
Q.push(temp->left);
if (temp->right)
Q.push(temp->right);
}
}

return depth;
}
};

参考博文链接:https://cuijiahua.com/blog/2018/01/basis_38.html

文章作者:zerofly

发布时间:2020年05月30日 - 16:05

原始链接:http://zeroflycui.github.io/fc8ea05.html

许可协议: 转载请保留原文链接及作者。