Question:
Given a binary tree, return the postorder traversal of its nodes’ values.
Thought:
Use a stack, and a cur value to see if we have reached the left node,then we pop from the stack, for inorder, we can just visit the node, but for post order, we need to check if the node has right child. If it has right child, null out its right child, push back to stack, and make the node equals its right child.
public List<Integer> postorderTraversal(TreeNode root) { Stack<TreeNode> stack= new Stack<>(); List<Integer> result = new ArrayList<>(); TreeNode cur= root; while(!stack.isEmpty()||cur!=null){ if(cur!=null){ stack.push(cur); cur=cur.left; }else{ cur=stack.pop(); if(cur.right!=null){ TreeNode right=cur.right; cur.right=null; stack.push(cur); cur=right; }else{ result.add(cur.val); cur=cur.right;//bug.. } } } return result; }