forked from soulmachine/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchapTree.tex
2054 lines (1592 loc) · 53.8 KB
/
chapTree.tex
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\chapter{树}
LeetCode 上二叉树的节点定义如下:
\begin{Code}
// 树的节点
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) { }
};
\end{Code}
\section{二叉树的遍历} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
树的遍历有两类:深度优先遍历和宽度优先遍历。深度优先遍历又可分为两种:先根(次序)遍历和后根(次序)遍历。
树的先根遍历是:先访问树的根结点,然后依次先根遍历根的各棵子树。树的先跟遍历的结果与对应二叉树(孩子兄弟表示法)的先序遍历的结果相同。
树的后根遍历是:先依次后根遍历树根的各棵子树,然后访问根结点。树的后跟遍历的结果与对应二叉树的中序遍历的结果相同。
二叉树的先根遍历有:\textbf{先序遍历}(root->left->right),root->right->left;后根遍历有:\textbf{后序遍历}(left->right->root),right->left->root;二叉树还有个一般的树没有的遍历次序,\textbf{中序遍历}(left->root->right)。
\subsection{Binary Tree Preorder Traversal}
\label{sec:binary-tree-preorder-traversal}
\subsubsection{描述}
Given a binary tree, return the \emph{preorder} traversal of its nodes' values.
For example:
Given binary tree \code{\{1,\#,2,3\}},
\begin{Code}
1
\
2
/
3
\end{Code}
return \code{[1,2,3]}.
Note: Recursive solution is trivial, could you do it iteratively?
\subsubsection{分析}
用栈或者Morris遍历。
\subsubsection{栈}
\begin{Code}
// LeetCode, Binary Tree Preorder Traversal
// 使用栈,时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> result;
stack<const TreeNode *> s;
if (root != nullptr) s.push(root);
while (!s.empty()) {
const TreeNode *p = s.top();
s.pop();
result.push_back(p->val);
if (p->right != nullptr) s.push(p->right);
if (p->left != nullptr) s.push(p->left);
}
return result;
}
};
\end{Code}
\subsubsection{Morris先序遍历}
\begin{Code}
// LeetCode, Binary Tree Preorder Traversal
// Morris先序遍历,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> result;
TreeNode *cur = root, *prev = nullptr;
while (cur != nullptr) {
if (cur->left == nullptr) {
result.push_back(cur->val);
prev = cur; /* cur刚刚被访问过 */
cur = cur->right;
} else {
/* 查找前驱 */
TreeNode *node = cur->left;
while (node->right != nullptr && node->right != cur)
node = node->right;
if (node->right == nullptr) { /* 还没线索化,则建立线索 */
result.push_back(cur->val); /* 仅这一行的位置与中序不同 */
node->right = cur;
prev = cur; /* cur刚刚被访问过 */
cur = cur->left;
} else { /* 已经线索化,则删除线索 */
node->right = nullptr;
/* prev = cur; 不能有这句,cur已经被访问 */
cur = cur->right;
}
}
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Binary Tree Inorder Traversal,见 \S \ref{sec:binary-tree-inorder-traversal}
\item Binary Tree Postorder Traversal,见 \S \ref{sec:binary-tree-postorder-traversal}
\item Recover Binary Search Tree,见 \S \ref{sec:recover-binary-search-tree}
\myenddot
\subsection{Binary Tree Inorder Traversal}
\label{sec:binary-tree-inorder-traversal}
\subsubsection{描述}
Given a binary tree, return the \emph{inorder} traversal of its nodes' values.
For example:
Given binary tree \code{\{1,\#,2,3\}},
\begin{Code}
1
\
2
/
3
\end{Code}
return \code{[1,3,2]}.
Note: Recursive solution is trivial, could you do it iteratively?
\subsubsection{分析}
用栈或者Morris遍历。
\subsubsection{栈}
\begin{Code}
// LeetCode, Binary Tree Inorder Traversal
// 使用栈,时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> result;
stack<const TreeNode *> s;
const TreeNode *p = root;
while (!s.empty() || p != nullptr) {
if (p != nullptr) {
s.push(p);
p = p->left;
} else {
p = s.top();
s.pop();
result.push_back(p->val);
p = p->right;
}
}
return result;
}
};
\end{Code}
\subsubsection{Morris中序遍历}
\begin{Code}
// LeetCode, Binary Tree Inorder Traversal
// Morris中序遍历,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> result;
TreeNode *cur = root, *prev = nullptr;
while (cur != nullptr) {
if (cur->left == nullptr) {
result.push_back(cur->val);
prev = cur;
cur = cur->right;
} else {
/* 查找前驱 */
TreeNode *node = cur->left;
while (node->right != nullptr && node->right != cur)
node = node->right;
if (node->right == nullptr) { /* 还没线索化,则建立线索 */
node->right = cur;
/* prev = cur; 不能有这句,cur还没有被访问 */
cur = cur->left;
} else { /* 已经线索化,则访问节点,并删除线索 */
result.push_back(cur->val);
node->right = nullptr;
prev = cur;
cur = cur->right;
}
}
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Binary Tree Preorder Traversal,见 \S \ref{sec:binary-tree-preorder-traversal}
\item Binary Tree Postorder Traversal,见 \S \ref{sec:binary-tree-postorder-traversal}
\item Recover Binary Search Tree,见 \S \ref{sec:recover-binary-search-tree}
\myenddot
\subsection{Binary Tree Postorder Traversal}
\label{sec:binary-tree-postorder-traversal}
\subsubsection{描述}
Given a binary tree, return the \emph{postorder} traversal of its nodes' values.
For example:
Given binary tree \code{\{1,\#,2,3\}},
\begin{Code}
1
\
2
/
3
\end{Code}
return \code{[3,2,1]}.
Note: Recursive solution is trivial, could you do it iteratively?
\subsubsection{分析}
用栈或者Morris遍历。
\subsubsection{栈}
\begin{Code}
// LeetCode, Binary Tree Postorder Traversal
// 使用栈,时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> result;
stack<const TreeNode *> s;
/* p,正在访问的结点,q,刚刚访问过的结点*/
const TreeNode *p = root, *q = nullptr;
do {
while (p != nullptr) { /* 往左下走*/
s.push(p);
p = p->left;
}
q = nullptr;
while (!s.empty()) {
p = s.top();
s.pop();
/* 右孩子不存在或已被访问,访问之*/
if (p->right == q) {
result.push_back(p->val);
q = p; /* 保存刚访问过的结点*/
} else {
/* 当前结点不能访问,需第二次进栈*/
s.push(p);
/* 先处理右子树*/
p = p->right;
break;
}
}
} while (!s.empty());
return result;
}
};
\end{Code}
\subsubsection{Morris后序遍历}
\begin{Code}
// LeetCode, Binary Tree Postorder Traversal
// Morris后序遍历,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> result;
TreeNode dummy(-1);
TreeNode *cur, *prev = nullptr;
std::function < void(const TreeNode*)> visit =
[&result](const TreeNode *node){
result.push_back(node->val);
};
dummy.left = root;
cur = &dummy;
while (cur != nullptr) {
if (cur->left == nullptr) {
prev = cur; /* 必须要有 */
cur = cur->right;
} else {
TreeNode *node = cur->left;
while (node->right != nullptr && node->right != cur)
node = node->right;
if (node->right == nullptr) { /* 还没线索化,则建立线索 */
node->right = cur;
prev = cur; /* 必须要有 */
cur = cur->left;
} else { /* 已经线索化,则访问节点,并删除线索 */
visit_reverse(cur->left, prev, visit);
prev->right = nullptr;
prev = cur; /* 必须要有 */
cur = cur->right;
}
}
}
return result;
}
private:
// 逆转路径
static void reverse(TreeNode *from, TreeNode *to) {
TreeNode *x = from, *y = from->right, *z;
if (from == to) return;
while (x != to) {
z = y->right;
y->right = x;
x = y;
y = z;
}
}
// 访问逆转后的路径上的所有结点
static void visit_reverse(TreeNode* from, TreeNode *to,
std::function< void(const TreeNode*) >& visit) {
TreeNode *p = to;
reverse(from, to);
while (true) {
visit(p);
if (p == from)
break;
p = p->right;
}
reverse(to, from);
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Binary Tree Preorder Traversal,见 \S \ref{sec:binary-tree-preorder-traversal}
\item Binary Tree Inorder Traversal,见 \S \ref{sec:binary-tree-inorder-traversal}
\item Recover Binary Search Tree,见 \S \ref{sec:recover-binary-search-tree}
\myenddot
\subsection{Binary Tree Level Order Traversal}
\label{sec:binary-tree-level-order-traversal}
\subsubsection{描述}
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree \code{\{3,9,20,\#,\#,15,7\}},
\begin{Code}
3
/ \
9 20
/ \
15 7
\end{Code}
return its level order traversal as:
\begin{Code}
[
[3],
[9,20],
[15,7]
]
\end{Code}
\subsubsection{分析}
无
\subsubsection{递归版}
\begin{Code}
// LeetCode, Binary Tree Level Order Traversal
// 递归版,时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int>> result;
traverse(root, 1, result);
return result;
}
void traverse(TreeNode *root, size_t level, vector<vector<int>> &result) {
if (!root) return;
if (level > result.size())
result.push_back(vector<int>());
result[level-1].push_back(root->val);
traverse(root->left, level+1, result);
traverse(root->right, level+1, result);
}
};
\end{Code}
\subsubsection{迭代版}
\begin{Code}
// LeetCode, Binary Tree Level Order Traversal
// 迭代版,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int> > result;
queue<TreeNode*> current, next;
if(root == nullptr) {
return result;
} else {
current.push(root);
}
while (!current.empty()) {
vector<int> level; // elments in one level
while (!current.empty()) {
TreeNode* node = current.front();
current.pop();
level.push_back(node->val);
if (node->left != nullptr) next.push(node->left);
if (node->right != nullptr) next.push(node->right);
}
result.push_back(level);
swap(next, current);
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Binary Tree Level Order Traversal II,见 \S \ref{sec:binary-tree-tevel-order-traversal-ii}
\item Binary Tree Zigzag Level Order Traversal,见 \S \ref{sec:binary-tree-zigzag-level-order-traversal}
\myenddot
\subsection{Binary Tree Level Order Traversal II}
\label{sec:binary-tree-tevel-order-traversal-ii}
\subsubsection{描述}
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree \code{\{3,9,20,\#,\#,15,7\}},
\begin{Code}
3
/ \
9 20
/ \
15 7
\end{Code}
return its bottom-up level order traversal as:
\begin{Code}
[
[15,7]
[9,20],
[3],
]
\end{Code}
\subsubsection{分析}
在上一题(见\S \ref{sec:binary-tree-tevel-order-traversal})的基础上,\fn{reverse()}一下即可。
\subsubsection{递归版}
\begin{Code}
// LeetCode, Binary Tree Level Order Traversal II
// 递归版,时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) {
vector<vector<int>> result;
traverse(root, 1, result);
std::reverse(result.begin(), result.end()); // 比上一题多此一行
return result;
}
void traverse(TreeNode *root, size_t level, vector<vector<int>> &result) {
if (!root) return;
if (level > result.size())
result.push_back(vector<int>());
result[level-1].push_back(root->val);
traverse(root->left, level+1, result);
traverse(root->right, level+1, result);
}
};
\end{Code}
\subsubsection{迭代版}
\begin{Code}
// LeetCode, Binary Tree Level Order Traversal II
// 迭代版,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) {
vector<vector<int> > result;
if(root == nullptr) return result;
queue<TreeNode*> current, next;
vector<int> level; // elments in level level
current.push(root);
while (!current.empty()) {
while (!current.empty()) {
TreeNode* node = current.front();
current.pop();
level.push_back(node->val);
if (node->left != nullptr) next.push(node->left);
if (node->right != nullptr) next.push(node->right);
}
result.push_back(level);
level.clear();
swap(next, current);
}
reverse(result.begin(), result.end()); // 比上一题多此一行
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Binary Tree Level Order Traversal,见 \S \ref{sec:binary-tree-tevel-order-traversal}
\item Binary Tree Zigzag Level Order Traversal,见 \S \ref{sec:binary-tree-zigzag-level-order-traversal}
\myenddot
\subsection{Binary Tree Zigzag Level Order Traversal}
\label{sec:binary-tree-zigzag-level-order-traversal}
\subsubsection{描述}
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree \code{{3,9,20,\#,\#,15,7}},
\begin{Code}
3
/ \
9 20
/ \
15 7
\end{Code}
return its zigzag level order traversal as:
\begin{Code}
[
[3],
[20,9],
[15,7]
]
\end{Code}
\subsubsection{分析}
广度优先遍历,用一个bool记录是从左到右还是从右到左,每一层结束就翻转一下。
\subsubsection{递归版}
\begin{Code}
// LeetCode, Binary Tree Zigzag Level Order Traversal
// 递归版,时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int>> result;
traverse(root, 1, result, true);
return result;
}
void traverse(TreeNode *root, size_t level, vector<vector<int>> &result,
bool left_to_right) {
if (!root) return;
if (level > result.size())
result.push_back(vector<int>());
if (left_to_right)
result[level-1].push_back(root->val);
else
result[level-1].insert(result[level-1].begin(), root->val);
traverse(root->left, level+1, result, !left_to_right);
traverse(root->right, level+1, result, !left_to_right);
}
};
\end{Code}
\subsubsection{迭代版}
\begin{Code}
// LeetCode, Binary Tree Zigzag Level Order Traversal
// 广度优先遍历,用一个bool记录是从左到右还是从右到左,每一层结束就翻转一下。
// 迭代版,时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int> > result;
queue<TreeNode*> current, next;
bool left_to_right = true;
if(root == nullptr) {
return result;
} else {
current.push(root);
}
while (!current.empty()) {
vector<int> level; // elments in one level
while (!current.empty()) {
TreeNode* node = current.front();
current.pop();
level.push_back(node->val);
if (node->left != nullptr) next.push(node->left);
if (node->right != nullptr) next.push(node->right);
}
if (!left_to_right) reverse(level.begin(), level.end());
result.push_back(level);
left_to_right = !left_to_right;
swap(next, current);
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Binary Tree Level Order Traversal,见 \S \ref{sec:binary-tree-tevel-order-traversal}
\item Binary Tree Level Order Traversal II,见 \S \ref{sec:binary-tree-tevel-order-traversal-ii}
\myenddot
\subsection{Recover Binary Search Tree}
\label{sec:recover-binary-search-tree}
\subsubsection{描述}
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note: A solution using $O(n)$ space is pretty straight forward. Could you devise a constant space solution?
\subsubsection{分析}
$O(n)$空间的解法是,开一个指针数组,中序遍历,将节点指针依次存放到数组里,然后寻找两处逆向的位置,先从前往后找第一个逆序的位置,然后从后往前找第二个逆序的位置,交换这两个指针的值。
中序遍历一般需要用到栈,空间也是$O(n)$的,如何才能不使用栈?Morris中序遍历。
\subsubsection{代码}
\begin{Code}
// LeetCode, Recover Binary Search Tree
// Morris中序遍历,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
void recoverTree(TreeNode* root) {
pair<TreeNode*, TreeNode*> broken;
TreeNode* prev = nullptr;
TreeNode* cur = root;
while (cur != nullptr) {
if (cur->left == nullptr) {
detect(broken, prev, cur);
prev = cur;
cur = cur->right;
} else {
auto node = cur->left;
while (node->right != nullptr && node->right != cur)
node = node->right;
if (node->right == nullptr) {
node->right = cur;
//prev = cur; 不能有这句!因为cur还没有被访问
cur = cur->left;
} else {
detect(broken, prev, cur);
node->right = nullptr;
prev = cur;
cur = cur->right;
}
}
}
swap(broken.first->val, broken.second->val);
}
void detect(pair<TreeNode*, TreeNode*>& broken, TreeNode* prev,
TreeNode* current) {
if (prev != nullptr && prev->val > current->val) {
if (broken.first == nullptr) {
broken.first = prev;
} //不能用else,例如 {0,1},会导致最后 swap时second为nullptr,
//会 Runtime Error
broken.second = current;
}
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Binary Tree Inorder Traversal,见 \S \ref{sec:binary-tree-inorder-traversal}
\myenddot
\subsection{Same Tree}
\label{sec:same-tree}
\subsubsection{描述}
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
\subsubsection{分析}
无
\subsubsection{递归版}
递归版
\begin{Code}
// LeetCode, Same Tree
// 递归版,时间复杂度O(n),空间复杂度O(logn)
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
if (!p && !q) return true; // 终止条件
if (!p || !q) return false; // 剪枝
return p->val == q->val // 三方合并
&& isSameTree(p->left, q->left)
&& isSameTree(p->right, q->right);
}
};
\end{Code}
\subsubsection{迭代版}
\begin{Code}
// LeetCode, Same Tree
// 迭代版,时间复杂度O(n),空间复杂度O(logn)
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
stack<TreeNode*> s;
s.push(p);
s.push(q);
while(!s.empty()) {
p = s.top(); s.pop();
q = s.top(); s.pop();
if (!p && !q) continue;
if (!p || !q) return false;
if (p->val != q->val) return false;
s.push(p->left);
s.push(q->left);
s.push(p->right);
s.push(q->right);
}
return true;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Symmetric Tree,见 \S \ref{sec:symmetric-tree}
\myenddot
\subsection{Symmetric Tree}
\label{sec:symmetric-tree}
\subsubsection{描述}
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
\subsubsection{分析}
无
\subsubsection{递归版}
\begin{Code}
// LeetCode, Symmetric Tree
// 递归版,时间复杂度O(n),空间复杂度O(logn)
class Solution {
public:
bool isSymmetric(TreeNode *root) {
if (root == nullptr) return true;
return isSymmetric(root->left, root->right);
}
bool isSymmetric(TreeNode *p, TreeNode *q) {
if (p == nullptr && q == nullptr) return true; // 终止条件
if (p == nullptr || q == nullptr) return false; // 终止条件
return p->val == q->val // 三方合并
&& isSymmetric(p->left, q->right)
&& isSymmetric(p->right, q->left);
}
};
\end{Code}
\subsubsection{迭代版}
\begin{Code}
// LeetCode, Symmetric Tree
// 迭代版,时间复杂度O(n),空间复杂度O(logn)
class Solution {
public:
bool isSymmetric (TreeNode* root) {
if (!root) return true;
stack<TreeNode*> s;
s.push(root->left);
s.push(root->right);
while (!s.empty ()) {
auto p = s.top (); s.pop();
auto q = s.top (); s.pop();
if (!p && !q) continue;
if (!p || !q) return false;
if (p->val != q->val) return false;
s.push(p->left);
s.push(q->right);
s.push(p->right);
s.push(q->left);
}
return true;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Same Tree,见 \S \ref{sec:same-tree}
\myenddot
\subsection{Balanced Binary Tree}
\label{sec:balanced-binary-tree}
\subsubsection{描述}
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
\subsubsection{分析}
无
\subsubsection{代码}
\begin{Code}
// LeetCode, Balanced Binary Tree
// 时间复杂度O(n),空间复杂度O(logn)
class Solution {
public:
bool isBalanced (TreeNode* root) {
return balancedHeight (root) >= 0;
}
/**
* Returns the height of `root` if `root` is a balanced tree,
* otherwise, returns `-1`.
*/
int balancedHeight (TreeNode* root) {
if (root == nullptr) return 0; // 终止条件
int left = balancedHeight (root->left);
int right = balancedHeight (root->right);
if (left < 0 || right < 0 || abs(left - right) > 1) return -1; // 剪枝
return max(left, right) + 1; // 三方合并
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{Flatten Binary Tree to Linked List}
\label{sec:flatten-binary-tree-to-linked-list}
\subsubsection{描述}
Given a binary tree, flatten it to a linked list in-place.
For example, Given
\begin{Code}
1
/ \
2 5
/ \ \
3 4 6
\end{Code}
The flattened tree should look like:
\begin{Code}
1
\
2
\
3
\
4
\
5
\
6
\end{Code}
\subsubsection{分析}
无
\subsubsection{递归版1}
\begin{Code}
// LeetCode, Flatten Binary Tree to Linked List
// 递归版1,时间复杂度O(n),空间复杂度O(logn)
class Solution {
public:
void flatten(TreeNode *root) {
if (root == nullptr) return; // 终止条件
flatten(root->left);
flatten(root->right);
if (nullptr == root->left) return;
// 三方合并,将左子树所形成的链表插入到root和root->right之间
TreeNode *p = root->left;
while(p->right) p = p->right; //寻找左链表最后一个节点
p->right = root->right;
root->right = root->left;
root->left = nullptr;
}
};
\end{Code}
\subsubsection{递归版2}
\begin{Code}
// LeetCode, Flatten Binary Tree to Linked List