-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path104.二叉树的最大深度.c
More file actions
117 lines (92 loc) · 2.19 KB
/
104.二叉树的最大深度.c
File metadata and controls
117 lines (92 loc) · 2.19 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
/*
* @lc app=leetcode.cn id=104 lang=c
*
* [104] 二叉树的最大深度
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
// 第二版,使用栈进行搜索,因为没有什么特殊要求也不需要做什么操作,
// 这里使用栈是一个不错的选择
int maxDepth(struct TreeNode* root){
struct TreeNode* stack_first[1024];
struct TreeNode* stack_tail[1024];
int headf = 0, headt = 0;
stack_first[headf++] = root;
bool flag = true;
int count = 0;
while (headt || headf)
{
bool sign = false;
for (int i = 0; flag && i < headf && stack_first[i]; i++)
{
if(stack_first[i]->left)
stack_tail[headt++] = stack_first[i]->left;
if(stack_first[i]->right)
stack_tail[headt++] = stack_first[i]->right;
sign = true;
}
flag = false;
headf = 0;
if (sign)
{
count++;
sign = false;
}
for (int i = 0; !flag && i < headt; i++)
{
if(stack_tail[i]->left)
stack_first[headf++] = stack_tail[i]->left;
if(stack_tail[i]->right)
stack_first[headf++] = stack_tail[i]->right;
sign = true;
}
flag = true;
headt = 0;
if (sign)
{
count++;
}
}
return count;
}
/* // 第一版,递归搜索二叉树
int Max(int left, int right)
{
if (left > right)
return left;
else
return right;
}
int Along_tree(struct TreeNode* tree)
{
if (tree == NULL)
{
return 0;
}
else if(tree->left && tree->right)
{
return Max(Along_tree(tree->left), Along_tree(tree->right)) + 1;
}
else if(tree->left)
{
return Along_tree(tree->left) + 1;
}
else if(tree->right)
{
return Along_tree(tree->right) + 1;
}
else
{
return 1;
}
}
int maxDepth(struct TreeNode* root){
return Along_tree(root);
}
*/