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

Note: Recursive solution is trivial, could you do it iteratively?

/**
 * 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) {
        Stack<StackNode> stack = new Stack<StackNode>();
        List<Integer> list = new ArrayList<Integer>();
        while(root != null){
            while(root.left != null){
                StackNode stackNode = new StackNode(root,0);
                stack.push(stackNode);
                root = root.left;
            }
            if(root.right != null){
                StackNode stackNode = new StackNode(root,1);
                stack.push(stackNode);
                root = root.right;
            }else{//叶子节点
                list.add(root.val);
                while(!stack.empty()){
                    StackNode node = stack.peek();//返回栈顶元素
                    if(node.flag == 1){//访问过右子树
                        node = stack.pop();
                        list.add(node.t.val);
                    }else{//访问完左子树
                        if(node.t.right != null){//有右子树
                            node.flag = 1;
                            root = node.t.right;
                            break;
                        }else{//没有右子树
                            list.add(node.t.val);
                            stack.pop();
                        }
                    }
                }
            }
            if(stack.empty()){
                break;
            }
        }
        return list;
    }
    public class StackNode{
        TreeNode t;
        int flag;//标志遍历的是左边还是右边,如果是遍历完右子树,就退栈,0标志正在遍历左子树,1标志正在遍历右子树
        public StackNode(TreeNode p,int f){
            t = p;
            flag = f;
        }
    } 
}

Runtime:  360 ms

这个题关键是需要记录下遍历的方向(左子树还是右子树,从而来确定父节点是否退栈),这个与迭代的前序和中序不同

你可能感兴趣的:(LeetCode,tree,binary,Postorde)