forked from leetcoders/LeetCode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTreeInorderTraversal.java
85 lines (83 loc) · 2.45 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
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
/*
Author: King, [email protected]
Date: Dec 20, 2014
Problem: Binary Tree Inorder Traversal
Difficulty: Easy
Source: https://oj.leetcode.com/problems/binary-tree-inorder-traversal/
Notes:
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
Solution: 1. Recursive solution. Time: O(n), Space: O(n).
2. Iterative way (stack). Time: O(n), Space: O(n).
3. Threaded tree (Morris). Time: O(n), Space: O(1).
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal_1(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if (root == null) return res;
inorder(root, res);
return res;
}
public void inorder(TreeNode root, List<Integer> res) {
if (root == null) return;
inorder(root.left, res);
res.add(root.val);
inorder(root.right, res);
}
public List<Integer> inorderTraversal_2(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
Stack<TreeNode> stk = new Stack<TreeNode>();
TreeNode cur = root;
while (stk.isEmpty() == false || cur != null) {
if (cur != null) {
stk.push(cur);
cur = cur.left;
} else {
cur = stk.pop();
res.add(cur.val);
cur = cur.right;
}
}
return res;
}
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
TreeNode cur = root;
while (cur != null) {
if (cur.left == null) {
res.add(cur.val);
cur = cur.right;
} else {
TreeNode node = cur.left;
while (node.right != null && node.right != cur)
node = node.right;
if (node.right == null) {
node.right = cur;
cur = cur.left;
} else {
res.add(cur.val);
node.right = null;
cur = cur.right;
}
}
}
return res;
}
}