Skip to content

Commit 3edfd74

Browse files
authored
Create 6.3.1树的高度.md
1 parent bb593bc commit 3edfd74

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed

6.3.1树的高度.md

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
- 问题:
2+
- 树的高度定义为从根节点到任何叶节点到最长路径上的节点数。编写一个函数来计算任意二叉树的高度。
3+
- 例子:
4+
- 下图中的二叉树深度为4。因为从根节点到叶子节点的最长路径涉及了4个节点。
5+
6+
![image](https://github.com/fmxs/ProgrammingInterviewsExposed_CodeImplement/assets/65701532/12551f35-3f8e-44b4-8717-b3e7e2072bd5)
7+
8+
9+
- 思路:
10+
- 先确保自己理解对题目中高度的定义。接着,找到关键点“二叉树”,这意味着每个节点最多只有2个子节点。
11+
- 首先猜想节点的高度是子节点的高度的总和,但是通过快速检查可以发现这样不正确。节点的高度其实是由左右子节点中更大的那一个节点的高度所决定的。
12+
- 所以树的高度等于其子树的最大高度 + 1。这是一个递归定义。
13+
- 代码实现:
14+
15+
```cpp
16+
#include <iostream>
17+
#include <algorithm>
18+
using namespace std;
19+
20+
struct TreeNode{
21+
int value;
22+
TreeNode* lChild;
23+
TreeNode* rChild;
24+
};
25+
26+
int GetDepth(TreeNode* root, int depth){
27+
if(root == nullptr){
28+
return depth;
29+
}
30+
31+
int lDepth = GetDepth(root->lChild, depth + 1);
32+
int rDepth = GetDepth(root->rChild, depth + 1);
33+
return std::max(lDepth, rDepth);
34+
}
35+
36+
TreeNode* GetTree3(){
37+
// 创建一个简单的二叉树
38+
TreeNode* root = new TreeNode();
39+
root->value = 1;
40+
41+
root->lChild = new TreeNode();
42+
root->lChild->value = 2;
43+
44+
root->rChild = new TreeNode();
45+
root->rChild->value = 3;
46+
47+
root->lChild->lChild = nullptr;
48+
root->lChild->rChild = nullptr;
49+
50+
root->rChild->lChild = new TreeNode();
51+
root->rChild->lChild->value = 4;
52+
53+
root->rChild->rChild = nullptr;
54+
return root;
55+
}
56+
57+
TreeNode* GetTree4(){
58+
// 创建一个简单的二叉树
59+
TreeNode* root = new TreeNode();
60+
root->value = 1;
61+
62+
root->lChild = new TreeNode();
63+
root->lChild->value = 2;
64+
65+
root->rChild = new TreeNode();
66+
root->rChild->value = 3;
67+
68+
root->lChild->lChild = nullptr;
69+
root->lChild->rChild = nullptr;
70+
71+
root->rChild->lChild = new TreeNode();
72+
root->rChild->lChild->value = 4;
73+
74+
root->rChild->rChild = new TreeNode();
75+
root->rChild->rChild->value = 5;
76+
77+
root->rChild->lChild->lChild = new TreeNode();
78+
root->rChild->lChild->lChild->value = 6;
79+
80+
root->rChild->lChild->rChild = new TreeNode();
81+
root->rChild->lChild->rChild->value = 7;
82+
83+
root->rChild->rChild->rChild = new TreeNode();
84+
root->rChild->rChild->rChild->value = 8;
85+
86+
return root;
87+
}
88+
89+
int main(){
90+
TreeNode* root3 = GetTree3();
91+
int depth1 = GetDepth(root3, 0);
92+
cout << "The depth of the binary tree is: " << depth1 << endl;// 3
93+
94+
TreeNode* root4 = GetTree4();
95+
int depth2 = GetDepth(root4, 0);
96+
cout << "The depth of the binary tree is: " << depth2 << endl;// 4
97+
98+
return 0;
99+
}
100+
```

0 commit comments

Comments
 (0)