LeetCode 7 Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes' values.

分析:

递归解法比较直观。

/**
 * Definition for binary tree
 * 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> result = new ArrayList<Integer>();
        postorderTraversal(root, result);
        return result;
    }
    
    private void postorderTraversal(TreeNode node, List<Integer> result){
        if(node == null) return;
        if(node.left != null)
            postorderTraversal(node.left, result);
        if(node.right != null)
            postorderTraversal(node.right, result);
        result.add(node.val);
    }
}
非递归解法,需要一个栈来辅助。访问左孩子之前把父节点压栈知道叶子,弹栈访问父节点之前先检查父节点的右孩子有没有访问过,如果没有,访问右孩子先。

/**
 * Definition for binary tree
 * 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> result = new ArrayList<Integer>();
        if(root == null) return result;
        Stack<TreeNode> st = new Stack<TreeNode>();
        TreeNode node = root;
        TreeNode pre = node;
        while(node != null || st.size() > 0){
            //沿左孩子遍历到树叶,将沿途节点全部压栈
            while(node != null){
                st.push(node);
                node = node.left;
            }
            if(st.size()>0){
                TreeNode right = st.peek().right;
                //如果右边节点是空或者刚刚处理过,则可以处理当前节点
                if(right == null || right == pre){
                    pre = st.pop();
                    result.add(pre.val);
                }else{
                    node = right;
                }
            }
        }
        return result;
    }
}



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