LeetCode -- Binary Tree Postorder Traversal
Question:
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?
Analysis:
给出一棵二叉树,返回树的结点的后序遍历。
Note:递归的解决方法是简单的,你能不用递归来实现吗?
思路一:递归解决:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { List<Integer> ll = new ArrayList<Integer>(); public List<Integer> postorderTraversal(TreeNode root) { post(root); return ll; } public void post(TreeNode root) { if(root == null) return; if(root.left != null) post(root.left); if(root.right != null) post(root.right); ll.add(root.val); } }
思路二:非递归解决。相较于二叉树的前序遍历和中序遍历,后续遍历更加复杂。当遍历完左子树还不能访问根结点,需要再遍历右子树。所以在我们的栈中,除了保存结点信息外还要说明目前遍历的结点是在是在上层根结点的左子树还是右子树中。
首先使用栈暂存根结点的信息,然后向左子树遍历下去,此时根结点的flag为“L”。当访问完左子树中结点并从左子树退回时,还要去遍历根的右子树,此时更改根结点的flag为“R”。访问完右子树才能访问根结点的值。
Answer:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<Integer>(); Stack<TreeNode> node = new Stack<TreeNode>(); Stack<Integer> flag = new Stack<Integer>(); //1 means the left, 2 means the right. TreeNode p = root; do { while(p != null) { node.push(p); flag.push(1); p = p.left; } boolean contin = true; while(contin && !node.isEmpty()) { p = node.pop(); int f = flag.pop(); switch(f) { case 1: f = 2; node.push(p); flag.push(f); contin = false; p = p.right; break; case 2: list.add(p.val); break; } } } while(!node.isEmpty()); return list; } }