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].

输出一颗树的后序遍历序列。我们可以用递归和迭代两种方法。用迭代时我们借助堆栈,因为是后序遍历,顺序为左-右-根,因此我们只需要通过根-右-左的顺序进行遍历,然后将序列翻转就可以了。代码如下:
递归:
/**
 * 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 postorderTraversal(TreeNode root) {
        List list = new ArrayList();
        if(root == null) return list;
        getPostorder(root, list);
        return list;
    }
    public void getPostorder(TreeNode root, List list) {
        if(root == null) return;
        getPostorder(root.left, list);
        getPostorder(root.right, list);
        list.add(root.val);
    }
}


迭代:
/**
 * 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 postorderTraversal(TreeNode root) {
        LinkedList list = new LinkedList();
        Stack stack = new Stack();
        if(root == null) return list;
        stack.add(root);
        while(!stack.isEmpty()) {
            TreeNode node = stack.pop();
            list.addFirst(node.val);
            if(node.left != null) {
                stack.push(node.left);
            }
            if(node.right != null) {
                stack.push(node.right);
            }
        }
        return list;
    }
}

你可能感兴趣的:(后序遍历,二叉树)