-
Notifications
You must be signed in to change notification settings - Fork 160
/
Tree.md
2807 lines (2177 loc) · 71.2 KB
/
Tree.md
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
<span id = "00"></span>
基础
- [144. Binary Tree Preorder Traversal](#144-binary-tree-preorder-traversal)
- [94. Binary Tree Inorder Traversal](#94-binary-tree-inorder-traversal)
- [145. Binary Tree Postorder Traversal](#145-binary-tree-postorder-traversal)
- [102. Binary Tree Level Order Traversal](#102-binary-tree-level-order-traversal)
- [107. Binary Tree Level Order Traversal II](#107-binary-tree-level-order-traversal-ii)
- [103. Binary Tree Zigzag Level Order Traversal](#103-binary-tree-zigzag-level-order-traversal)
- [100. Same Tree](#100-same-tree)
- [101. Symmetric Tree](#101-symmetric-tree)
- [226. Invert Binary Tree](#226-invert-binary-tree)
- [257. Binary Tree Paths](#257-binary-tree-paths)
- [112. Path Sum](#112-path-sum)
- [113. Path Sum II](#113-path-sum-ii)
- [129. Sum Root to Leaf Numbers](#129-sum-root-to-leaf-numbers)
- [298 Binary Tree Longest Consecutive Sequence] **?**
- [111. Minimum Depth of Binary Tree](#111-minimum-depth-of-binary-tree)
- [104. Maximum Depth of Binary Tree](#104-maximum-depth-of-binary-tree)
- [662. Maximum Width of Binary Tree](#662-maximum-width-of-binary-tree)
- [559. Maximum Depth of N-ary Tree](#559-maximum-depth-of-n-ary-tree)
- [110. Balanced Binary Tree](#110-balanced-binary-tree)
- [124. Binary Tree Maximum Path Sum](#124-binary-tree-maximum-path-sum)
- [250 Count Univalue Subtrees] **?**
- [366 Find Leaves of Binary Tree] **?**
- [337. House Robber III](#337-house-robber-iii)
- [617. Merge Two Binary Trees](#617-merge-two-binary-trees)
- [199. Binary Tree Right Side View](#199-binary-tree-right-side-view)
BST
- [98. Validate Binary Search Tree](#98-validate-binary-search-tree)
- [235. Lowest Common Ancestor of a Binary Search Tree](#235-lowest-common-ancestor-of-a-binary-search-tree)
- [236. Lowest Common Ancestor of a Binary Tree](#236-lowest-common-ancestor-of-a-binary-tree)
- [1123. Lowest Common Ancestor of Deepest Leaves](#1123-lowest-common-ancestor-of-deepest-leaves)
- [108. Convert Sorted Array to Binary Search Tree](#108-convert-sorted-array-to-binary-search-tree)
- [109. Convert Sorted List to Binary Search Tree](#109-convert-sorted-list-to-binary-search-tree)
- [173. Binary Search Tree Iterator](#173-binary-search-tree-iterator)
- [230. Kth Smallest Element in a BST](#230-kth-smallest-element-in-a-bst)
- [297. Serialize and Deserialize Binary Tree](#297-serialize-and-deserialize-binary-tree)
- [285 Inorder Successor in BST] **?**
- [270 Closest Binary Search Tree Value] **?**
- [272 Closest Binary Search Tree Value II] **?**
- [99. Recover Binary Search Tree](#99-recover-binary-search-tree)
重要程度
- [156 Binary Tree Upside Down] **?**
- [114. Flatten Binary Tree to Linked List](#114-flatten-binary-tree-to-linked-list)
- [255 Verify Preorder Sequence in Binary Search Tree] **?**
- [333 Largest BST Subtree] **?**
- [222. Count Complete Tree Nodes](#222-count-complete-tree-nodes)
- [105. Construct Binary Tree from Preorder and Inorder Traversal](#105-construct-binary-tree-from-preorder-and-inorder-traversal)
- [106. Construct Binary Tree from Inorder and Postorder Traversal](#106-construct-binary-tree-from-inorder-and-postorder-traversal)
- [116. Populating Next Right Pointers in Each Node](#116-populating-next-right-pointers-in-each-node)
- [117. Populating Next Right Pointers in Each Node II](#117-populating-next-right-pointers-in-each-node-ii)
- [314 Binary Tree Vertical Order Traversal] **?**
- [96. Unique Binary Search Trees](#96-unique-binary-search-trees)
- [95. Unique Binary Search Trees II](#95-unique-binary-search-trees-ii)
- [331. Verify Preorder Serialization of a Binary Tree](#331-verify-preorder-serialization-of-a-binary-tree)
- [968. Binary Tree Cameras](#968-binary-tree-cameras)
## 144. Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values.
给定一个二叉树,返回其节点值的前序遍历。
**Example**
```
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,2,3]
```
---
### Python Solution
**分析:** 分为两个解法,一种是递归的做法,另外一种是迭代的做法。
```python
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
res = []
self.dfs(root, res)
return res
def dfs(self,root, res):
if root:
res.append(root.val)
self.dfs(root.left, res)
self.dfs(root.right, res)
# More easier
class Solution:
def preorderTraversal(self, root):
return [] if not root else [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)
```
**迭代法**
```python
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
stack, res = [root], []
while stack:
node = stack.pop()
if node:
res.append(node.val)
stack.append(node.right)
stack.append(node.left)
return res
```
[返回目录](#00)
## 94. Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes' values.
给定一个二叉树,返回其节点值的中序遍历。
**Example**
```
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
```
---
### Python Solution
**分析:** 分为两个解法,一种是递归的做法,另外一种是迭代的做法。
```python
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
self.dfs(root, res)
return res
def dfs(self,root, res):
if root:
self.dfs(root.left, res)
res.append(root.val)
self.dfs(root.right, res)
# More easier
class Solution:
def inorderTraversal(self, root):
return [] if not root else self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)
```
**迭代法**
```python
class Solution:
def inorderTraversal(self, root):
res, stack = [], []
while stack or root:
while root:
stack.append(root)
root = root.left
node = stack.pop()
res.append(node.val)
root = node.right
return res
```
[返回目录](#00)
## 145. Binary Tree Postorder Traversal
Given a binary tree, return the postorder traversal of its nodes' values.
给定一个二叉树,返回其节点值的后序遍历。
**Example**
```
Input: [1,null,2,3]
1
\
2
/
3
Output: [3,2,1]
```
---
### Python Solution
**分析:** 分为两个解法,一种是递归的做法,另外一种是迭代的做法。
```python
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
res = []
self.dfs(root, res)
return res
def dfs(self,root, res):
if root:
self.dfs(root.left, res)
self.dfs(root.right, res)
res.append(root.val)
# More easier
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val] if root else []
```
**迭代法**
```python
class Solution:
def postorderTraversal(self, root):
stack, res = [root], []
while stack:
node = stack.pop()
if node:
res.append(node.val)
stack.append(node.left)
stack.append(node.right)
return res[::-1]
```
[返回目录](#00)
## 102. Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
给定一个二叉树,返回其节点值的层次遍历。 (即,从左到右,逐级)。
**Example**
```
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
```
---
### Python Solution
**分析:** 分层存储,每次输出当层并且将下一层的在赋值到这里。
```python
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
if root:
level = [root]
while level:
res.append([node.val for node in level])
level = [kid for node in level for kid in (node.left, node.right) if kid]
return res
```
[返回目录](#00)
## 107. Binary Tree Level Order Traversal II
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).
给定一个二叉树,返回其节点值的自下而上的级别顺序遍历。 (即,从左到右,从叶到根逐级)。
**Example**
```
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
```
---
### Python Solution
**分析:** 分层存储,每次输出当层并且将下一层的在赋值到这里。
```python
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
res = []
if root:
level = [root]
while level:
res.append([node.val for node in level])
level = [kid for node in level for kid in (node.left, node.right) if kid]
return res[::-1]
```
[返回目录](#00)
## 103. Binary Tree Zigzag Level Order Traversal
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).
给定一个二叉树,返回其节点值的之字形级别顺序遍历。 (即,从左到右,然后从右到左进入下一个级别,并在它们之间交替)。
**Example**
```
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
```
---
### Python Solution
**分析:** 分层存储,每次输出当层并且将下一层的在赋值到这里。
```python
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
if root:
level = [root]
flag = 1
while level:
res.append([node.val for node in level][::flag])
level = [kid for node in level for kid in (node.left, node.right) if kid]
flag *= -1
return res
```
[返回目录](#00)
## 100. Same Tree
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
给定两个二进制树,编写一个函数来检查它们是否相同。
如果两个二叉树在结构上相同并且节点具有相同的值,则认为它们是相同的。
**Example**
```
Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
```
---
### Python Solution
**分析:** 递归和迭代法。推荐递归。
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if p and q:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return p is q
```
**DFS**
```Python
class Solution:
def isSameTree(self, p, q):
stack = [(p, q)]
while stack:
n1, n2 = stack.pop()
if n1 and n2 and n1.val == n2.val:
stack.append((n1.right, n2.right))
stack.append((n1.left, n2.left))
elif n1 is n2:
continue
else:
return False
return True
```
**BFS**
```Python
class Solution:
def isSameTree(self, p, q):
dq = collections.deque([(p, q)])
while dq:
n1, n2 = dq.popleft()
if n1 and n2 and n1.val == n2.val:
dq.extend([(n1.left, n2.left), (n1.right, n2.right)])
elif n1 is n2:
continue
else:
return False
return True
```
[返回目录](#00)
## 101. Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
给定一棵二叉树,检查它是否是其自身的镜像(即,围绕其中心对称)。
**Example**
```
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
```
---
### Python Solution
**分析:** 分为两个解法,一种是递归的做法,另外一种是迭代的做法。
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
return self.compare(root.left, root.right)
def compare(self, p, q):
if p and q:
return p.val == q.val and self.compare(p.left, q.right) and self.compare(p.right, q.left)
return p is q
```
**迭代法**
```python
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
dq = collections.deque([(root.left, root.right)])
while dq:
l, r = dq.popleft()
if l and r and l.val == r.val:
dq.extend([(l.right, r.left), (l.left, r.right)])
elif l is r:
continue
else:
return False
return True
```
[返回目录](#00)
## 226. Invert Binary Tree
Invert a binary tree.
左右翻转二叉树。
**Example**
```
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
```
---
### Python Solution
**分析:** 分为两个解法,一种是递归的做法,另外一种是迭代的做法。
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if root:
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
```
**迭代法**
```python
class Solution:
def invertTree(self, root):
stack = [root]
while stack:
node = stack.pop()
if node:
node.left, node.right = node.right, node.left
stack.extend([node.left, node.right])
return root
```
[返回目录](#00)
## 257. Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.
给定一棵二叉树,返回所有从根到叶的路径。
**Example**
```
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
```
---
### Python Solution
**分析:** 分为两个解法,一种是递归的做法,另外一种是迭代的做法。
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def binaryTreePaths(self, root):
if not root:
return []
return [str(root.val) + '->' + path
for kid in (root.left, root.right) if kid
for path in self.binaryTreePaths(kid)] or [str(root.val)]
```
**迭代法**
```python
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if not root:
return []
paths, stack = [], [(root, str(root.val))]
while stack:
node, path = stack.pop()
if not node.left and not node.right:
paths.append(path)
if node.left:
stack.append((node.left, path + '->' + str(node.left.val)))
if node.right:
stack.append((node.right, path + '->' + str(node.right.val)))
return paths
```
[返回目录](#00)
## 112. Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
给定一个二叉树和一个和,确定该树是否具有从根到叶的路径,以使该路径上的所有值加起来等于给定的和。
**Example**
```
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
```
---
### Python Solution
**分析:** 分为两个解法,一种是递归的做法,另外一种是迭代的做法。
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def hasPathSum(self, root, sum):
if not root:
return False
if not root.left and not root.right and root.val == sum:
return True
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
```
**迭代法**
```python
class Solution:
def hasPathSum(self, root, sum):
if not root:
return False
stack = [(root, root.val)]
while stack:
node, cur = stack.pop()
if not node.left and not node.right and cur == sum:
return True
if node.left:
stack.append((node.left, cur + node.left.val))
if node.right:
stack.append((node.right, cur + node.right.val))
return False
```
[返回目录](#00)
## 113. Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
给定一棵二叉树和一个和,找到所有从根到叶的路径,其中每个路径的和等于给定的和。
**Example**
```
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
[
[5,4,11,2],
[5,8,4,5]
]
```
---
### Python Solution
**分析:** 分为两个解法,一种是递归的做法,另外一种是迭代的做法。
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathSum(self, root: TreeNode, tsum: int) -> List[List[int]]:
if not root :
return []
temp, res = [], []
def DFTS(root):
temp.append(root.val)
if not root.left and not root.right and sum(temp) == tsum:
res.append(temp.copy())
if root.left:
DFTS(root.left)
if root.right:
DFTS(root.right)
temp.pop()
DFTS(root)
return res
```
**迭代法**
```python
class Solution:
def pathSum(self, root: TreeNode, Psum: int) -> List[List[int]]:
if not root:
return []
stack, res = [(root, [root.val])], []
while stack:
node, cur = stack.pop()
if not node.left and not node.right and sum(cur) == Psum:
res.append(cur)
if node.left:
stack.append((node.left, cur + [node.left.val]))
if node.right:
stack.append((node.right, cur + [node.right.val]))
return res
```
[返回目录](#00)
## 129. Sum Root to Leaf Numbers
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
给定一个仅包含0-9数字的二叉树,每个从根到叶的路径都可以表示一个数字。
一个示例是从根到叶的路径1-> 2-> 3,它表示数字123。
找到所有从根到叶的数字的总和。
**Example**
```
Input: [4,9,0,5,1]
4
/ \
9 0
/ \
5 1
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.
```
---
### Python Solution
**分析:** 分为两个解法,一种是递归的做法,另外一种是迭代的做法。
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
def f(root):
if not root:
return []
return [str(root.val) + path
for kid in (root.left, root.right) if kid
for path in f(kid)] or [str(root.val)]
return sum(map(int,f(root)))
```
**迭代法**
```python
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
if not root:
return 0
stack, res = [(root, str(root.val))], 0
while stack:
node, st = stack.pop()
if not node.left and not node.right:
res += int(st)
if node.left:
stack.append((node.left, st + str(node.left.val)))
if node.right:
stack.append((node.right, st + str(node.right.val)))
return res
```
[返回目录](#00)
## 111. Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
给定二叉树,找到其最小深度。 最小深度是沿着从根节点到最近的叶节点的最短路径的节点数。
**Example**
```
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
```
---
### Python Solution
**分析:** 分为两个解法,一种是递归的做法,另外一种是迭代的做法。
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root):
if not root: return 0
d = list(map(self.minDepth, (root.left, root.right)))
return 1 + (min(d) or max(d))
class Solution:
def minDepth(self, root):
if not root:
return 0
if not root.left:
return self.minDepth(root.right) + 1
if not root.right:
return self.minDepth(root.left) + 1
return 1 + min(self.minDepth(root.right), self.minDepth(root.left))
```
**迭代法**
```python
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
stack, res = [(root, 1)], float('inf')
while stack:
node, depth = stack.pop()
if not node.left and not node.right:
res = min(res, depth)
if node.left:
stack.append((node.left, depth + 1))
if node.right:
stack.append((node.right, depth + 1))
return res
```
[返回目录](#00)
## 104. Maximum Depth of Binary Tree
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.
Note: A leaf is a node with no children.
给定二叉树,找到其最大深度。
最大深度是沿着从根节点到最远叶节点的最长路径的节点数。
注意:叶子是没有子节点的节点。
**Example**
```
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \