-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0111_minDepth.cc
102 lines (99 loc) · 2.07 KB
/
Problem_0111_minDepth.cc
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <algorithm>
#include <cstdint>
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
class Solution
{
public:
int minDepth1(TreeNode* root)
{
if (root == nullptr)
{
return 0;
}
if (root->left == nullptr && root->right == nullptr)
{
return 1;
}
int ans = INT32_MAX;
if (root->left != nullptr)
{
ans = std::min(ans, minDepth1(root->left));
}
if (root->right != nullptr)
{
ans = std::min(ans, minDepth1(root->right));
}
return ans + 1;
}
// Morris
int minDepth2(TreeNode* root)
{
if (root == nullptr)
{
return 0;
}
TreeNode* cur = root;
TreeNode* mostRight = nullptr;
// 上一个节点所在的层数
int preLevel = 0;
// 树的右边界长度
int rightLen = 0;
int ans = INT32_MAX;
while (cur != nullptr)
{
mostRight = cur->left;
if (mostRight != nullptr)
{
rightLen = 1;
while (mostRight->right != nullptr && mostRight->right != cur)
{
rightLen++;
mostRight = mostRight->right;
}
if (mostRight->right == nullptr)
{
preLevel++;
mostRight->right = cur;
cur = cur->left;
continue;
}
else
{
if (mostRight->left == nullptr)
{
ans = std::min(ans, preLevel);
}
preLevel -= rightLen;
mostRight->right = nullptr;
}
}
else
{
preLevel++;
}
cur = cur->right;
}
// 不要忘了整棵树的最右节点
rightLen = 1;
cur = root;
while (cur->right != nullptr)
{
rightLen++;
cur = cur->right;
}
// 整棵树的最右节点是叶节点才纳入统计
if (cur->left == nullptr)
{
ans = std::min(ans, rightLen);
}
return ans;
}
};