-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLC94.java
97 lines (84 loc) · 2.33 KB
/
LC94.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
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
94. Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
*/
//Approach 1: 'recursive'
class Solution
{
public List < Integer > inorderTraversal(TreeNode root)
{
List < Integer > res = new ArrayList < > ();
recursive(root, res);
return res;
}
public void recursive(TreeNode root, List < Integer > res) {
if (root != null)
{
if (root.left != null) {
recursive(root.left, res);
}
res.add(root.val);
if (root.right != null) {
recursive(root.right, res);
}
}
}
}
//Approach 2: 'Iterating using stack'
public class Solution
{
public List < Integer > inorderTraversal(TreeNode root)
{
List < Integer > res = new ArrayList < > ();
Stack < TreeNode > stack = new Stack < > ();
TreeNode curr = root;
while (curr != null || !stack.isEmpty())
{
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
res.add(curr.val);
curr = curr.right;
}
return res;
}
}
//Approach 3: Morris Traversal
//In this method, we have to use a new data structure-Threaded Binary Tree
class Solution
{
public List < Integer > inorderTraversal(TreeNode root)
{
List < Integer > res = new ArrayList < > ();
TreeNode curr = root;
TreeNode pre;
while (curr != null)
{
if (curr.left == null) {
res.add(curr.val);
curr = curr.right; // move to next right node
}
else { // has a left subtree
pre = curr.left;
while (pre.right != null) { // find rightmost
pre = pre.right;
}
pre.right = curr; // put cur after the pre node
TreeNode temp = curr; // store cur node
curr = curr.left; // move cur to the top of the new tree
temp.left = null; // original cur left be null, avoid infinite loops
}
}
return res;
}
}