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 {
    private Stack<TreeNode> stack = new Stack<>();
	private void leftDown(TreeNode node){
		while (node != null) {
			stack.push(node);
			node = node.left;
		}
	}
	public ArrayList<Integer> postorderTraversal(TreeNode root) {
		ArrayList<Integer> res = new ArrayList<>();
        leftDown(root);
        TreeNode last = null;
        while (!stack.isEmpty()) {
			TreeNode node = stack.peek();
			TreeNode right = node.right;
			if (right != null && node.right != last) {
				leftDown(right);
			}
			else{
				stack.pop();
				res.add(node.val);
				last = node;
			}
		}
        return res;
    }
}



你可能感兴趣的:(Binary Tree Postorder Traversal)