-
-
Notifications
You must be signed in to change notification settings - Fork 605
Expand file tree
/
Copy pathBinaryTreeInorderTraversal.java
More file actions
42 lines (35 loc) · 983 Bytes
/
BinaryTreeInorderTraversal.java
File metadata and controls
42 lines (35 loc) · 983 Bytes
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
package problems.medium;
import problems.utils.TreeNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* Created by sherxon on 1/3/17.
*/
// recursive and iterative solutions
public class BinaryTreeInorderTraversal {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<>();
// inOrder(root, list);
inOrderIterative(root, list);
return list;
}
private void inOrderIterative(TreeNode x, List<Integer> list) {
Stack<TreeNode> stack=new Stack<>();
while (x!=null || !stack.isEmpty()){
while(x!=null){
stack.add(x);
x=x.left;
}
x=stack.pop();
list.add(x.val);
x=x.right;
}
}
void inOrder(TreeNode x, List<Integer> list){
if(x==null)return;
inOrder(x.left, list);
list.add(x.val);
inOrder(x.right,list);
}
}