[Java Solution]using stack with a isVisited status property


  • 0
    public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res=new ArrayList<Integer>();
        Stack<DefinedTreeNode> s=new Stack<DefinedTreeNode>();
        if(root==null)
            return res;
        s.push(new DefinedTreeNode(root, false));
        DefinedTreeNode dt;
        while(!s.empty()){
            dt=s.peek();
            if(dt.isVisited){
                res.add(dt.node.val);
                s.pop();
            }
            else{
                if(dt.node.right!=null)
                    s.push(new DefinedTreeNode(dt.node.right, false));
                if(dt.node.left!=null)
                    s.push(new DefinedTreeNode(dt.node.left, false));
                dt.isVisited=true;
            }
        }
        return res;
        
    }
    }
     class DefinedTreeNode{
    TreeNode node;
    boolean isVisited;
    public DefinedTreeNode(TreeNode node, boolean isVisited){
        this.node=node;
        this.isVisited=isVisited;
    }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.