forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTree.tex
More file actions
3285 lines (2518 loc) · 76.1 KB
/
Tree.tex
File metadata and controls
3285 lines (2518 loc) · 76.1 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
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{Tree}
\subsubsection{500以上的题目暂时未录入}
\section{Maximum Depth of Binary Tree} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
\subsubsection{Solution}
\begin{Code}
private int maxDepth(TreeNode node) {
if (node == null) {
return 0;
}
return Math.max(maxDepth(node.left), maxDepth(node.right)) + 1;
}
\end{Code}
\newpage
\section{Invert Binary Tree} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Invert a binary tree.
\begin{Code}
4 4
/ \ / \
2 7 to 7 2
/ \ / \ / \ / \
1 3 6 9 9 6 3 1
\end{Code}
\subsubsection{Solution I}
\begin{Code}
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode right = root.right;
root.right = invertTree(root.left);
root.left = invertTree(right);
return root;
}
\end{Code}
\subsubsection{Solution II}
\begin{Code}
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
TreeNode left = node.left;
node.left = node.right;
node.right = left;
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
return root;
}
\end{Code}
\newpage
\section{Same Tree} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
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{Solution}
\begin{Code}
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
\end{Code}
\newpage
\section{Binary Search Tree Iterator} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
\textbf{Note:}
next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
\subsubsection{Solution}
\begin{Code}
public class BSTIterator {
private Stack<TreeNode> mStack;
private TreeNode mCurNode;
public BSTIterator(TreeNode root) {
mStack = new Stack<TreeNode>();
mCurNode = root;
}
public boolean hasNext() {
return !mStack.isEmpty() || mCurNode != null;
}
public int next() {
int result = -1;
while (hasNext()) {
if (mCurNode != null) {
mStack.push(mCurNode);
mCurNode = mCurNode.left;
} else {
mCurNode = mStack.pop();
result = mCurNode.val;
mCurNode = mCurNode.right;
break;
}
}
return result;
}
}
\end{Code}
\newpage
\section{Lowest Common Ancestor of a Binary Search Tree} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
\begin{Code}
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5
\end{Code}
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
\subsubsection{Solution}
\begin{Code}
// 耗时9ms
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (!checkExist(root, p) || !checkExist(root, q)) {
throw new IllegalArgumentException("Not exist!!");
}
while (root != null) {
if (p.val < root.val && q.val < root.val) {
root = root.left;
} else if (p.val > root.val && q.val > root.val) {
root = root.right;
} else {
break;
}
}
return root;
}
/**
* 如何判断p或q一定存在,如果是BST就很简单
*/
private boolean checkExist(TreeNode root, TreeNode node) {
TreeNode cur = root;
while (cur != null) {
if (node.val > cur.val) {
cur = cur.right;
} else if (node.val < cur.val) {
cur = cur.left;
} else {
return true;
}
}
return false;
}
\end{Code}
\newpage
\section{Balanced Binary Tree} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
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{Solution}
\begin{Code}
public boolean isBalanced(TreeNode root) {
return isBalanced(root, null);
}
private boolean isBalanced(TreeNode root, int[] height) {
if (root == null) {
return true;
}
int[] left = new int[1], right = new int[1];
boolean result = isBalanced(root.left, left) && isBalanced(root.right, right);
if (height != null) {
height[0] = Math.max(left[0], right[0]) + 1;
}
return result && Math.abs(left[0] - right[0]) <= 1;
}
\end{Code}
\newpage
\section{Binary Tree Maximum Path Sum} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
For example:
Given the below binary tree,
\begin{Code}
1
/ \
2 3
\end{Code}
Return 6.
\subsubsection{Solution}
\begin{Code}
public int maxPathSum(TreeNode root) {
return maxPathSum(root, null);
}
/**
* max表示包含root的单边路径最大和
*/
private int maxPathSum(TreeNode root, int[] max) {
if (root == null) {
return Integer.MIN_VALUE; // 此处容易错
}
int[] left = new int[1], right = new int[1];
int leftMax = maxPathSum(root.left, left);
int rightMax = maxPathSum(root.right, right);
if (max != null) {
// 三种情况:root, root+left, root+right
max[0] = max(left[0], right[0], 0) + root.val;
}
// 容易错,要考虑到所有可能的情况
// 左边里面的,右边里面的,光root的,左中右,左中,中右
return max(leftMax, rightMax, root.val, left[0] + right[0] + root.val,
left[0] + root.val, right[0] + root.val);
}
private int max(int... vals) {
int max = Integer.MIN_VALUE;
for (int val : vals) {
max = Math.max(max, val);
}
return max;
}
\end{Code}
\newpage
\section{Populating Next Right Pointers in Each Node} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given a binary tree
\begin{Code}
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
\end{Code}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
\textbf{Note:}
You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
\begin{Code}
1
/ \
2 3
/ \ / \
4 5 6 7
\end{Code}
After calling your function, the tree should look like:
\begin{Code}
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
\end{Code}
\newpage
\subsubsection{Solution I}
\begin{Code}
/** 递归法,巧妙地运用dummy使代码很简洁
* 假定当前root所在层已连好,要连下一层
*/
public void connect(TreeLinkNode root) {
if (root == null) {
return;
}
TreeLinkNode dummy = new TreeLinkNode(0), cur = dummy;
for (TreeLinkNode p = root; p != null; p = p.next) {
if (p.left != null) {
cur.next = p.left;
cur = cur.next;
}
if (p.right != null) {
cur.next = p.right;
cur = cur.next;
}
}
connect(dummy.next);
}
\end{Code}
\subsubsection{Solution II}
\begin{Code}
/**
* 将递归转成非递归很简单,就加一层循环,且结尾处加root = dummy.next即可
*/
public void connect2(TreeLinkNode root) {
while (root != null) {
TreeLinkNode dummy = new TreeLinkNode(0), cur = dummy;
for (TreeLinkNode p = root; p != null; p = p.next) {
if (p.left != null) {
cur.next = p.left;
cur = cur.next;
}
if (p.right != null) {
cur.next = p.right;
cur = cur.next;
}
}
root = dummy.next;
}
}
\end{Code}
\newpage
\section{Convert Sorted Array to Binary Search Tree} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
\subsubsection{Solution}
\begin{Code}
public TreeNode sortedArrayToBST(int[] nums) {
return sortedArrayToBST(nums, 0, nums.length);
}
private TreeNode sortedArrayToBST(int[] nums, int start, int end) {
if (start >= end) {
return null;
}
int mid = start + (end - start) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = sortedArrayToBST(nums, start, mid);
root.right = sortedArrayToBST(nums, mid + 1, end);
return root;
}
\end{Code}
\newpage
\section{Symmetric Tree} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree \code{[1,2,2,3,4,4,3]} is symmetric:
\begin{Code}
1
/ \
2 2
/ \ / \
3 4 4 3
\end{Code}
But the following \code{[1,2,2,null,3,null,3]} is not:
\begin{Code}
1
/ \
2 2
\ \
3 3
\end{Code}
\textbf{Note:}
Bonus points if you could solve it both recursively and iteratively.
\subsubsection{Solution}
\begin{Code}
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return isSymmetric(root.left, root.right);
}
private boolean isSymmetric(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null) {
return false;
}
return left.val == right.val && isSymmetric(left.left, right.right)
&& isSymmetric(left.right, right.left);
}
\end{Code}
\newpage
\section{Lowest Common Ancestor of a Binary Tree} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
\begin{Code}
_______3______
/ \
___5__ ___1__
/ \ / \
6 _2 0 8
/ \
7 4
\end{Code}
For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
\subsubsection{Solution I}
\begin{Code}
/**
* leetcode测试用例中p和q一定是在树中的
* 奇怪的是如果判断用root.val == p.val这种就不能AC,必须用root == p
* 确实,树中可能会存在值重复的节点
*/
// 耗时11ms
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null) {
return right != null ? root : left;
} else {
return right;
}
}
\end{Code}
\newpage
\subsubsection{Solution II}
\begin{Code}
/**
* 这是迭代写法,另外考虑了p或者q不在树中的情况
* 用一个map保存每个node的前驱节点,当p和q同时找到了则回溯他们的前驱节点查看是否重合。
* 如果树遍历完了还没有同时找到p和q则返回null
*/
/**
* 耗时29ms
*/
public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || p == null || q == null) {
return null;
}
HashMap<TreeNode, TreeNode> parents = new HashMap<>();
parents.put(root, null);
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
if (parents.containsKey(p) && parents.containsKey(q)) {
break;
}
TreeNode node = queue.poll();
if (node.left != null) {
queue.add(node.left);
parents.put(node.left, node);
}
if (node.right != null) {
queue.add(node.right);
parents.put(node.right, node);
}
}
if (!parents.containsKey(p) || !parents.containsKey(q)) {
return null;
}
Set<TreeNode> set = new HashSet<TreeNode>();
for (TreeNode node = p; node != null; node = parents.get(node)) {
set.add(node);
}
for (TreeNode node = q; node != null; node = parents.get(node)) {
if (set.contains(node)) {
return node;
}
}
return null;
}
\end{Code}
\newpage
\section{Binary Tree Level Order Traversal} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
\begin{Code}
Given binary tree [3,9,20,null,null,15,7],
3 [
/ \ [3],
9 20 return its level order traversal as: [9,20],
/ \ [15,7]
15 7 ]
\end{Code}
\subsubsection{Solution}
\begin{Code}
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new LinkedList<List<Integer>>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
Queue<TreeNode> next = new LinkedList<TreeNode>();
queue.add(root);
List<Integer> cur = null;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (cur == null) {
cur = new LinkedList<Integer>();
result.add(cur);
}
cur.add(node.val);
if (node.left != null) {
next.add(node.left);
}
if (node.right != null) {
next.add(node.right);
}
if (queue.isEmpty()) {
Queue<TreeNode> temp = queue;
queue = next;
next = temp;
cur = null; // 注意这里要置空
}
}
return result;
}
\end{Code}
\newpage
\section{Binary Tree Level Order Traversal II} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
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 [3,9,20,null,null,15,7],
\begin{Code}
3
/ \
9 20
/ \
15 7
\end{Code}
return its bottom-up level order traversal as: [[15,7],[9,20],[3]]
\subsubsection{Solution}
\begin{Code}
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new LinkedList<List<Integer>>();
if (root == null) { return result;}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
Queue<TreeNode> next = new LinkedList<TreeNode>();
queue.add(root);
List<Integer> cur = null;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (cur == null) {
cur = new LinkedList<Integer>();
result.add(0, cur);
}
cur.add(node.val);
if (node.left != null) {
next.add(node.left);
}
if (node.right != null) {
next.add(node.right);
}
if (queue.isEmpty()) {
Queue<TreeNode> temp = queue;
queue = next;
next = temp;
cur = null; // 注意这里要置空
}
}
return result;
}
\end{Code}
\newpage
\section{Binary Tree Zigzag Level Order Traversal} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
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,null,null,15,7]},
\begin{Code}
3
/ \
9 20
/ \
15 7
\end{Code}
return its zigzag level order traversal as: \code{[[3],[20,9],[15,7]]}
\subsubsection{Solution}
\begin{Code}
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new LinkedList<List<Integer>>();
if (root == null) {return result;}
List<TreeNode> seq = new LinkedList<TreeNode>();
List<TreeNode> tmp = new LinkedList<TreeNode>();
seq.add(root);
List<Integer> cur = new LinkedList<Integer>();
for (int level = 1; !seq.isEmpty(); ) {
TreeNode node = seq.remove(0);
if (level % 2 != 0) {
cur.add(node.val);
} else {
cur.add(0, node.val);
}
if (node.left != null) {
tmp.add(node.left);
}
if (node.right != null) {
tmp.add(node.right);
}
if (seq.isEmpty()) {
result.add(cur);
cur = new LinkedList<Integer>();
List<TreeNode> tt = seq;
seq = tmp;
tmp = tt;
level++;
}
}
return result;
}
\end{Code}
\newpage
\section{Serialize and Deserialize Binary Tree} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
For example, you may serialize the following tree
\begin{Code}
1
/ \
2 3
/ \
4 5
\end{Code}
as \code{"[1,2,3,null,null,4,5]"}, just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
\newpage
\subsubsection{Solution I}
\begin{Code}
// 这里的分隔符是有讲究的,如果换成'.'则在split的时候要转义,但是','不用
private static final String SEP = ",";
// 这个尽可能短,节省空间
private static final String NULL = "X";
/** 递归版的 */
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
if (root != null) {
sb.append(root.val).append(SEP);
sb.append(serialize(root.left)).append(SEP);
sb.append(serialize(root.right));
} else {
sb.append(NULL);
}
return sb.toString();
}
public TreeNode deserialize(String data) {
String[] texts = data.split(SEP);
Queue<String> queue = new LinkedList<String>(Arrays.asList(texts));
return helper(queue);
}
private TreeNode helper(Queue<String> queue) {
if (queue.isEmpty()) {
return null;
}
String text = queue.poll();
if (text.equals(NULL)) {
return null;
}
int val = Integer.valueOf(text);
TreeNode root = new TreeNode(val);
root.left = helper(queue);
root.right = helper(queue);
return root;
}
\end{Code}
\newpage
\subsubsection{Solution II}
\begin{Code}
/** 下面是非递归版的DFS */
public String serialize2(TreeNode root) {
StringBuilder sb = new StringBuilder();
if (root == null) {
sb.append(NULL);
return sb.toString();
}
Stack<TreeNode> stack = new Stack<TreeNode>();
while (!stack.isEmpty() || root != null) {
if (root != null) {
sb.append(root.val);
stack.push(root);
root = root.left;
} else {
sb.append(NULL);
root = stack.pop().right;
}
sb.append(SEP);
}
return sb.toString();
}
public TreeNode deserialize2(String data) {
String[] texts = data.split(SEP);
Queue<String> queue = new LinkedList<String>(Arrays.asList(texts));
Deque<TreeNode> stack = new LinkedList<>();
TreeNode root = getNode(queue), node = root;
while (!queue.isEmpty()) {
if (node != null) {
stack.push(node);
node.left = getNode(queue);
node = node.left;
} else {
node = stack.pop();
node.right = getNode(queue);
node = node.right;
}
}
return root;
}
private TreeNode getNode(Queue<String> queue) {
if (queue.isEmpty()) {
return null;
}
String text = queue.poll();
if (text.equals(NULL)) {
return null;
}
return new TreeNode(Integer.parseInt(text));
}
\end{Code}
\newpage
\subsubsection{Solution III}
\begin{Code}
/**
* BFS版的
*/
public String serialize3(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
StringBuilder sb = new StringBuilder();
if (root == null) {
sb.append(NULL);
return sb.toString();
}
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node == null) {
sb.append(NULL).append(SEP);
continue;
}
sb.append(node.val).append(SEP);
queue.add(node.left);
queue.add(node.right);
}
return sb.toString();
}
public TreeNode deserialize3(String data) {
String[] text = data.split(SEP);
Queue<String> queue = new LinkedList<String>(Arrays.asList(text));
Queue<TreeNode> queue2 = new LinkedList<TreeNode>();
TreeNode root = getNode(queue);
queue2.add(root);
while (!queue2.isEmpty()) {
TreeNode node = queue2.poll();
if (node == null) {
continue;
}
node.left = getNode(queue);
queue2.add(node.left);
node.right = getNode(queue);
queue2.add(node.right);
}
return root;
}
\end{Code}
\newpage
\section{Count Complete Tree Nodes} %%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Description}
Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
\subsubsection{Solution}
\begin{Code}
/** 适合通用的二叉树,但是对于完全二叉树会超时
public int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
int count = 0;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
count++;
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}