1. 程式人生 > >[LintCode] Binary Tree Leaves Order Traversal

[LintCode] Binary Tree Leaves Order Traversal

eal child int div contains depth light hat ide

Given a binary tree, collect a tree‘s nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.

Have you met this question in a real interview? Yes Example

Given binary tree:

          1
         /         2   3
       / \     
      4   5    

Returns [[4, 5, 3], [2], [1]]

.

If we assign a value of 1 to all leave nodes as their height, then we can assign a value of 2 to the parent nodes of all leave nodes.

Repeat this from bottom up until we‘ve reached root node, which has the biggest height value. Since we need to start the assign

from bottom, we need to use depth first search. For leave nodes, they should be added from left to right, so for a given node,

its left child is visited first, then its right child.

To get the height of a given node, we need to get both children node‘s height first, then pick the bigger one plus 1. This is an indication

of post order traversal.

Algorithm:

1. do a post order traversal on given binary tree, assigning a height value to each node.

height = max {left child‘s height, right child‘s height} + 1;

add each node‘s value to a list and establish a mapping between height and a list.

Nodes with the same height are put in the same list. Post order ensures that all leave nodes are added

  from left side to right side.

2. Iterate all map keys in increasing order and get each list.

 1 public class Solution {
 2     private HashMap<Integer, List<Integer>> height = new HashMap<>();
 3     public List<List<Integer>> findLeaves(TreeNode root) {
 4         List<List<Integer>> result = new ArrayList<>();
 5         int max_Height = getNodeHeight(root);
 6         for(int i = 1; i <= max_Height; i++) {
 7             result.add(height.get(i));
 8         }
 9         return result;
10     }
11     
12     private int getNodeHeight(TreeNode node) {
13         if(node == null) {
14             return 0;
15         }
16         int leftH = getNodeHeight(node.left);
17         int rightH = getNodeHeight(node.right);
18         int h = Math.max(leftH, rightH) + 1;
19         if(!height.containsKey(h)) {
20             height.put(h, new ArrayList<Integer>());
21         }
22         height.get(h).add(node.val);
23         return h;
24     }
25 }

Related Problems

Minimum Depth of Binary Tree

Maximum Depth of Binary Tree

[LintCode] Binary Tree Leaves Order Traversal