-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBinaryTreeInorderTraversal.java
50 lines (45 loc) · 1.28 KB
/
BinaryTreeInorderTraversal.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
package leetcode;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* Created by Edward on 25/07/2017.
*/
public class BinaryTreeInorderTraversal {
/**
* 94. Binary Tree Inorder Traversal
* Given a binary tree, return the inorder traversal of its nodes' values.
* time : O(n)
* space : O(n)
* @param root
* @return
*/
public static List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res;
helper(res, root);
return res;
}
public static void helper(List<Integer> res, TreeNode root) {
if (root == null) return;
helper(res, root.left);
res.add(root.val);
helper(res, root.right);
}
public static List<Integer> inorderTraversal2(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
res.add(cur.val);
cur = cur.right;
}
return res;
}
}