-
Notifications
You must be signed in to change notification settings - Fork 0
/
inorder_traversal.java
51 lines (44 loc) · 1.37 KB
/
inorder_traversal.java
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//left- pop- right, use a node instead of root itself
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if(root == null) return res;
TreeNode node = root;
Stack<TreeNode> stack = new Stack<TreeNode>();
while(!stack.isEmpty() || node != null){
if(node != null){
stack.push(node);
node = node.left;
}else{
node = stack.pop();
res.add(node.val);
node = node.right;
}
}
return res;
}
}
//preoder traversal
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> tree = new ArrayList<Integer>();
if(root == null) return tree;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode top = stack.pop();
tree.add(top.val);
if(top.right != null) stack.push(top.right);
if(top.left != null) stack.push(top.left);
}
return tree;
}