-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeInorderTraversal_94.java
More file actions
84 lines (69 loc) · 2.24 KB
/
BinaryTreeInorderTraversal_94.java
File metadata and controls
84 lines (69 loc) · 2.24 KB
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
/**
* ----------------------------------------------------------------------------
Binary Tree Inorder Traversal
- Given a binary tree, return the inorder traversal of its nodes values
* ----------------------------------------------------------------------------
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/**
* 1. stack
* - O(n) time & O(logn) space
* - the left side will not go into the stack
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> inorder = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode curr = root;
while (!stack.isEmpty() || curr != null) {
while (curr != null) {
stack.push(curr); curr = curr.left;
}
curr = stack.pop();
inorder.add(curr.val);
curr = curr.right;
}
return inorder;
}
}
//------------------------------------------------------------------------------
/**
* 2. morris
* O(n) time O(1) space
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> inorder = new ArrayList<Integer>();
TreeNode curr = root, rightmost = null;
while (curr != null) {
if (curr.left == null) { // do not have a left subtree
inorder.add(new Integer(curr.val));
curr = curr.right;
continue;
}
// have a left subtree
// find the left subtree's right most
rightmost = curr.left;
while (rightmost.right != null && rightmost.right != curr)
rightmost = rightmost.right;
if (rightmost.right == null) { // first time
rightmost.right = curr;
curr = curr.left;
}
else { // second time
inorder.add(new Integer(curr.val));
rightmost.right = null;
curr = curr.right;
}
}
return inorder;
}
}