forked from leetcoders/LeetCode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTreePostorderTraversal.java
104 lines (99 loc) · 3.26 KB
/
BinaryTreePostorderTraversal.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
98
99
100
101
102
103
104
/*
Author: King, [email protected]
Date: Nov 20, 2014
Problem: Binary Tree Postorder Traversal
Difficulty: Easy
Source: http://oj.leetcode.com/problems/binary-tree-postorder-traversal/
Notes:
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
Solution: 1. Iterative way (stack). Time: O(n), Space: O(n).
2. Recursive solution. Time: O(n), Space: O(n).
3. Threaded tree (Morris). Time: O(n), Space: O(n/1).
Space: O(1) if in-place reverse.
You may refer to my blog for more detailed explanations:
http://www.cnblogs.com/AnnieKim/archive/2013/06/15/MorrisTraversal.html
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> postorderTraversal_1(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if (root == null) return res;
Stack<TreeNode> stk = new Stack<TreeNode>();
TreeNode cur = root;
TreeNode pre = null;
while (stk.isEmpty() == false || cur != null) {
if (cur != null) {
stk.push(cur);
cur = cur.left;
} else {
TreeNode peak = stk.peek();
if (peak.right != null && pre != peak.right) {
cur = peak.right;
} else {
res.add(peak.val);
stk.pop();
pre = peak;
}
}
}
return res;
}
public List<Integer> postorderTraversal_2(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if (root == null) return res;
List<Integer> left = postorderTraversal(root.left);
List<Integer> right = postorderTraversal(root.right);
res.addAll(left);
res.addAll(right);
res.add(root.val);
return res;
}
public List<Integer> postorderTraversal_3(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if (root == null) return res;
Stack<Integer> stk = new Stack<Integer>();
TreeNode dummy = new TreeNode(-1);
dummy.left = root;
TreeNode cur = dummy;
while (cur != null) {
if (cur.left == null) {
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 {
TreeNode temp = cur.left;
while (temp != cur) {
stk.push(temp.val);
temp = temp.right;
}
while (stk.isEmpty() == false) res.add(stk.pop());
node.right = null;
cur = cur.right;
}
}
}
return res;
}
}