lintcode66-67-68 Binary Tree (Postorder-Inorder-Postorder) Traversal 非递归(iterative)总结
Given a binary tree, return the preoder, inorder, postorder traversal of its nodes' values.
模板对
前序 | 中序 | 后序 | |
全局变量定义 |
ArrayList<Integer> result + Stack<TreeNode> stack 好基友 |
||
TreeNode curt |
TreeNode curt |
TreeNode prev,curt |
|
判断输入 | 都判root == null ?,最后看能不能合并,inorder其实可以 | ||
初始化 | push root | curt = root | push root, curt = root, prev = null |
while条件 | !stack.isEmpty() | curt != null || !stack.isEmpty() | !stack.isEmpty() |
while内部结构 | add中, 两个独立if去push右左 | while一直左下, add中, 赋值以处理右 |
curt = peek; 三个关联if处理下溯,左上溯,右上溯或叶子{ 下溯,两个关联if去push左右 左上溯,push右 右上溯,add } prev = curt; |
return |
1.preorder
public class Solution { public List<Integer> preorderTraversal(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); List<Integer> preorder = new ArrayList<Integer>(); if (root == null) { return preorder; } stack.push(root); while (!stack.empty()) { TreeNode node = stack.pop(); preorder.add(node.val); if (node.right != null) { stack.push(node.right); } if (node.left != null) { stack.push(node.left); } } return preorder; } }
2.inorder
public class Solution { /** * @param root: The root of binary tree. * @return: Inorder in ArrayList which contains node values. */ public ArrayList<Integer> inorderTraversal(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); ArrayList<Integer> result = new ArrayList<Integer>(); TreeNode curt = root; while (curt != null || !stack.empty()) { while (curt != null) { stack.add(curt); curt = curt.left; } curt = stack.pop(); result.add(curt.val); curt = curt.right; } return result; } }
3. postorder
public ArrayList<Integer> postorderTraversal(TreeNode root) { ArrayList<Integer> result = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode prev = null; // previously traversed node TreeNode curr = root; if (root == null) { return result; } stack.push(root); while (!stack.empty()) { curr = stack.peek(); if (prev == null || prev.left == curr || prev.right == curr) { // traverse down the tree if (curr.left != null) { stack.push(curr.left); } else if (curr.right != null) { stack.push(curr.right); } } else if (curr.left == prev) { // traverse up the tree from the left if (curr.right != null) { stack.push(curr.right); } } else { // traverse up the tree from the right result.add(curr.val); stack.pop(); } prev = curr; } return result; }