68 · Binary Tree Postorder Traversal - LintCode
# Description
Given a binary tree, return the postorder traversal of its nodes’ values.
- The first data is the root node, followed by the value of the left and right son nodes, and "#" indicates that there is no child node.
- The number of nodes does not exceed 20.
Example 1:
Input:
binary tree = {1,2,3}
Output:
[2,3,1]
# Solution
/** | |
* Definition of TreeNode: | |
* public class TreeNode { | |
* public int val; | |
* public TreeNode left, right; | |
* public TreeNode(int val) { | |
* this.val = val; | |
* this.left = this.right = null; | |
* } | |
* } | |
*/ | |
public class Solution { | |
/** | |
* @param root: A Tree | |
* @return: Postorder in ArrayList which contains node values. | |
*/ | |
public List<Integer> postorderTraversal(TreeNode root) { | |
List<Integer> result = new ArrayList<>(); | |
if (root == null){ | |
return result; | |
} | |
Stack<TreeNode> stack = new Stack<>(); | |
stack.push(root); | |
TreeNode prev = null; | |
while (!stack.isEmpty()){ | |
TreeNode curr = stack.peek(); | |
if (prev == null || prev.left == curr || prev.right == curr){ | |
if (curr.left != null){ | |
stack.push(curr.left); | |
} else if (curr.right != null){ | |
stack.push(curr.right); | |
} | |
} else if (curr.left == prev){ // traverse up to root, see the right node | |
if (curr.right != null){ | |
stack.push(curr.right); | |
} | |
} else { | |
result.add(curr.val); | |
stack.pop(); | |
} | |
prev = curr; | |
} | |
return result; | |
} | |
} |