https://leetcode.com/problems/binary-tree-postorder-traversal/description/
Description
Implement an iterative, post-order traversal of a given binary tree, return the list of keys of each node in the tree as it is post-order traversed.
Examples
5
/
3 8
/
1 4 11
Post-order traversal is [1, 4, 3, 11, 8, 5]
Corner Cases
- What if the given binary tree is null? Return an empty list in this case.
How is the binary tree represented?
We use the level order traversal sequence with a special symbol "#" denoting the null node.
For Example:
The sequence [1, 2, 3, #, #, 4] represents the following binary tree:
1
/
2 3
/
4
/**
* public class TreeNode {
* public int key;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int key) {
* this.key = key;
* }
* }
*/
1 public List<Integer> postOrder(TreeNode root) {
2 // Write your solution here
3 if(root == null ) return new ArrayList<Integer>() ;
4 List<Integer> res = new ArrayList<Integer>() ;
5 traverse(root, res) ;
6 return res ;
7 }
8 private void traverse(TreeNode root, List<Integer> res){
9 //base case
10 if(root == null ) return ;
11 traverse(root.left, res);
12 traverse(root.right, res) ;
13 res.add(root.key);
14 }