File tree 2 files changed +66
-1
lines changed
solution/094.Binary Tree Inorder Traversal
2 files changed +66
-1
lines changed Original file line number Diff line number Diff line change 18
18
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
19
19
20
20
### 解法
21
- 递归算法,先递归左子树,再访问根结点,最后递归右子树。
22
21
23
22
- 递归算法
24
23
24
+ 先递归左子树,再访问根结点,最后递归右子树。
25
+
25
26
``` java
26
27
27
28
/**
@@ -49,5 +50,42 @@ class Solution {
49
50
inorderTraversal(root. right, list);
50
51
}
51
52
53
+ }
54
+ ```
55
+
56
+ - 非递归算法
57
+
58
+ 一直向左找到结点的最左结点,中间每到一个结点,将结点压入栈中。到了最左结点时,输出该结点值,然后对该结点右孩子执行上述循环。
59
+
60
+ ``` java
61
+ /**
62
+ * Definition for a binary tree node.
63
+ * public class TreeNode {
64
+ * int val;
65
+ * TreeNode left;
66
+ * TreeNode right;
67
+ * TreeNode(int x) { val = x; }
68
+ * }
69
+ */
70
+ class Solution {
71
+ public List<Integer > inorderTraversal (TreeNode root ) {
72
+ List<Integer > list = new ArrayList<> ();
73
+ Stack<TreeNode > stack = new Stack<> ();
74
+
75
+ while (root != null || ! stack. isEmpty()) {
76
+ while (root != null ) {
77
+ stack. push(root);
78
+ root = root. left;
79
+ }
80
+ if (! stack. isEmpty()) {
81
+ root = stack. pop();
82
+ list. add(root. val);
83
+ root = root. right;
84
+ }
85
+ }
86
+ return list;
87
+
88
+ }
89
+
52
90
}
53
91
```
Original file line number Diff line number Diff line change
1
+ // 递归版本
2
+ /*
1
3
class Solution {
2
4
public List<Integer> inorderTraversal(TreeNode root) {
3
5
List<Integer> list = new ArrayList<>();
@@ -14,4 +16,29 @@ private void inorderTraversal(TreeNode root, List<Integer> list) {
14
16
inorderTraversal(root.right, list);
15
17
}
16
18
19
+ }
20
+
21
+ */
22
+
23
+ // 非递归版本
24
+ class Solution {
25
+ public List <Integer > inorderTraversal (TreeNode root ) {
26
+ List <Integer > list = new ArrayList <>();
27
+ Stack <TreeNode > stack = new Stack <>();
28
+
29
+ while (root != null || !stack .isEmpty ()) {
30
+ while (root != null ) {
31
+ stack .push (root );
32
+ root = root .left ;
33
+ }
34
+ if (!stack .isEmpty ()) {
35
+ root = stack .pop ();
36
+ list .add (root .val );
37
+ root = root .right ;
38
+ }
39
+ }
40
+ return list ;
41
+
42
+ }
43
+
17
44
}
You can’t perform that action at this time.
0 commit comments