-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSept2017-BinaryTreeInorderTraversal.java
More file actions
55 lines (48 loc) · 1.3 KB
/
Sept2017-BinaryTreeInorderTraversal.java
File metadata and controls
55 lines (48 loc) · 1.3 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
/*
Step 1: Initialize current as root
Step 2: While current is not NULL,
If current does not have left child
a. Add current’s value
b. Go to the right, i.e., current = current.right
Else
a. In current's left subtree, make current the right child of the rightmost node
b. Go to this left child, i.e., current = current.left
*/
public class TreeNode
{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
// using recursion is simple
// using morris traversal
class Solution
{
public List<Integer> inorderTraversal(TreeNode root)
{
List<Integer> res = new ArrayList<>();
TreeNode cur = root;
while (cur != null)
{
if (cur.left == null)
{
res.add(cur.val);
cur = cur.right;
}
else
{
TreeNode prev = cur.left;
while (prev.right != null)
{
prev = prev.right;
}
prev.right = cur;
TreeNode temp = cur;
cur = cur.left;
temp.left = null;
}
}
return res;
}
}