145. Binary Tree Postorder Traversal

同样的遍历过程,可以考虑用一个Stack保存先序遍历的结果,随后将stack内的值逐个POP。这里要求先左再右,如果在原有的遍历过程中仍然是以左半部分为优先的话,在pop后会变成右先左后,所以要从右边开始。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List postorderTraversal(TreeNode root) {
        List result = new ArrayList<>();
        Stack stack1 = new Stack<>();
        Stack stack2 = new Stack<>();
        TreeNode cur = root;
        while(!stack1.isEmpty()||cur!=null)
        {
            while(cur!=null)
            {
                stack2.push(cur.val);
                stack1.push(cur);
                cur=cur.right;
            }
            cur=stack1.pop().left;
        }
        while(!stack2.isEmpty())
        {
            result.add(stack2.pop());
        }
        return result ;
    }
}

你可能感兴趣的:(145. Binary Tree Postorder Traversal)