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]
.
题意:后续遍历二叉树
分类:二叉树
解法1:递归。
-
-
-
-
-
-
-
-
-
- public class Solution {
- public List<Integer> postorderTraversal(TreeNode root) {
- List<Integer> res = new ArrayList<Integer>();
- helper(root,res);
- return res;
- }
-
- public void helper(TreeNode root,List<Integer> res){
- if(root!=null&&root.left!=null) helper(root.left,res);
- if(root!=null&&root.right!=null) helper(root.right,res);
- if(root!=null) res.add(root.val);
- }
- }
解法2:使用栈进行遍历。对于根节点而已,将最左边的节点全部入栈。考察最后一个入栈的左节点,判断其右子树是否存在。如果不存在,访问这个节点,让这个节点退栈,接着访问上一个节点。
如果存在,先访问右子树。
-
-
-
-
-
-
-
-
-
- public class Solution {
- public List<Integer> postorderTraversal(TreeNode root) {
- List<Integer> res = new ArrayList<Integer>();
- if(root==null) return res;
- Stack<TreeNode> stack = new Stack<TreeNode>();
- TreeNode cur = root;
- do{
- while(cur!=null){
- stack.add(cur);
- cur = cur.left;
- }
- TreeNode p = null;
- while(!stack.isEmpty()){
- cur = stack.peek();
- if(cur.right==p){
- stack.pop();
- res.add(cur.val);
- p = cur;
- }else{
- cur = cur.right;
- break;
- }
- }
- }while(!stack.isEmpty());
- return res;
- }
- }
解法3:使用栈与双向链表。对于根节点而已,后续遍历时先左子树,在右子树,后根节点。
所以每次遍历,将相应节点添加到链表头部。所以顺序编程,先根节点,再右子树,后左子树。
-
-
-
-
-
-
-
-
-
- public class Solution {
- public List<Integer> postorderTraversal(TreeNode root) {
- LinkedList<Integer> res = new LinkedList<Integer>();
- if(root==null) return res;
- Stack<TreeNode> stack = new Stack<TreeNode>();
- stack.add(root);
- while(!stack.isEmpty()){
- TreeNode cur = stack.pop();
- res.addFirst(cur.val);
- if(cur.left!=null) stack.add(cur.left);
- if(cur.right!=null) stack.add(cur.right);
- }
- return res;
- }
- }
解法4:
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/46696117