My Easy Java Solution Using Stack


  • 0
    B
    public List<Integer> postorderTraversal(TreeNode root) {
            LinkedList<TreeNode> stk = new LinkedList<TreeNode>();
            List<Integer> result = new LinkedList<Integer>();
            if(root != null)
                stk.push(root);
            while(!stk.isEmpty()){
                TreeNode node = stk.peek();
                if(node.left == null && node.right == null)
                    result.add(stk.poll().val);
                else{
                    if(node.right != null){
                        stk.push(node.right);
                        node.right = null;//To prevent from repetitive operation for children of the node.
                    }
                    if(node.left != null){
                        stk.push(node.left);
                        node.left = null;//To prevent from repetitive operation for children of the node.
                    }
                }
            }
            return result;
        }
    

  • 0
    M

    Why change the input tree? Isn't it a common sense that input data should NOT be modified ?


  • 0
    B

    @MarathonRush The reason why I changed the input tree is to prevent repeatedly visiting on nodes. And I thought the return data has nothing to do with the input tree in this situation.


Log in to reply
 

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