My java iterative answer


  • 2
    J
    public class Solution {
        public List<Integer> postorderTraversal(TreeNode root) {
    		List<Integer> result = new ArrayList<Integer>();
    		if(root==null)  return result;
    		Stack<TreeNode> stack = new Stack<TreeNode>();
    		TreeNode cur;
    		TreeNode pre = null;
    				stack.push(root);
    
    		while (!stack.empty()) {
    			cur = stack.peek();
    			if ((cur.left == null && cur.right == null) || pre != null
    					&& (pre == cur.left || pre == cur.right)) {
    				result.add(cur.val);
    				stack.pop();
    				pre = cur;
    			}
    
    			else {
    				if (cur.right != null) {
    					stack.push(cur.right);
    				}
    				if (cur.left != null) {
    					stack.push(cur.left);
    				}
    
    			}
    
    		}
    
    		return result;
    	}
    }

  • 0
    M

    Nice solution, thanks for sharing.


Log in to reply
 

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