PostOrder
public class Solution {
// Important, when you pop a node, ensure its children are traversed.
public List<Integer> postorderTraversal(TreeNode root) {
ArrayDeque<TreeNode> s = new ArrayDeque();
List<Integer> ans = new ArrayList<Integer>();
TreeNode cur = root;
while (cur != null || !s.isEmpty()) {
while (cur != null) {
s.push(cur);
cur = cur.left;
}
while (!s.isEmpty() && cur == s.peek().right) {
cur = s.pop();
ans.add(cur.val);
}
if (s.isEmpty()) cur = null; else cur = s.peek().right;
}
return ans;
}
}
PreOrder
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<Integer>();
ArrayDeque<TreeNode> stk = new ArrayDeque<TreeNode>();
TreeNode cur = root;
while(cur != null || !stk.isEmpty()){
if(cur != null) {
stk.push(cur);
res.add(cur.val); // add val before going to children
cur = cur.left;
} else {
TreeNode node = stk.pop();
cur = node.right;
}
}
return res;
}
}
InOrder
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if(root == null) return res;
ArrayDeque<TreeNode> stk = new ArrayDeque<TreeNode>();
TreeNode cur = root;
while(cur != null || !stk.isEmpty()){
if(cur !=null) {
stk.push(cur);
cur = cur.left;
} else {
TreeNode node = stk.pop();
res.add(node.val); // add after all left children
node = node.right;
}
}
return res;
}
}
PreOrder
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<Integer>();
ArrayDeque<TreeNode> stk = new ArrayDeque<TreeNode>();
if(root == null) return res;
TreeNode cur = root;
stk.push(cur);
while(!stk.isEmpty()){
cur = stk.pop();
res.add(cur.val);
if(cur.right != null) stk.push(cur.right);
if(cur.left != null) stk.push(cur.left);
}
return res;
}
}
InOrder
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if(root == null) return res;
ArrayDeque<TreeNode> stk = new ArrayDeque<TreeNode>();
TreeNode cur = root;
while(cur != null || !stk.isEmpty()){
while(cur != null) {
stk.push(cur);
cur = cur.left;
}
cur = stk.pop();
res.add(cur.val);
cur = cur.right;
}
return res;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。