leetcode--Binary Tree Postorder Traversal

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:递归。

/**
 * 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> 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:使用栈进行遍历。对于根节点而已,将最左边的节点全部入栈。考察最后一个入栈的左节点,判断其右子树是否存在。如果不存在,访问这个节点,让这个节点退栈,接着访问上一个节点。

如果存在,先访问右子树。

/**
 * 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> 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:使用栈与双向链表。对于根节点而已,后续遍历时先左子树,在右子树,后根节点。

所以每次遍历,将相应节点添加到链表头部。所以顺序编程,先根节点,再右子树,后左子树。

/**
 * 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) {
        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:


你可能感兴趣的:(leetcode--Binary Tree Postorder Traversal)