Wednesday, December 28, 2016

Leetcode/F家,G家 -- 314. Binary Tree Vertical Order Traversal (BFS)


314. Binary Tree Vertical Order Traversal (BFS)
  • Difficulty: Medium
https://leetcode.com/problems/binary-tree-vertical-order-traversal/
Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).
If two nodes are in the same row and column, the order should be from left to right.
Examples:
  1. Given binary tree [3,9,20,null,null,15,7],
       3
      /\
     /  \
     9  20
        /\
       /  \
      15   7
    
    return its vertical order traversal as:
    [
      [9],
      [3,15],
      [20],
      [7]
    ]
    
  2. Given binary tree [3,9,8,4,0,1,7],
         3
        /\
       /  \
       9   8
      /\  /\
     /  \/  \
     4  01   7
    
    return its vertical order traversal as:
    [
      [4],
      [9],
      [3,0,1],
      [8],
      [7]
    ]
    
  3. Given binary tree [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5),
         3
        /\
       /  \
       9   8
      /\  /\
     /  \/  \
     4  01   7
        /\
       /  \
       5   2
    
    return its vertical order traversal as:
    [
      [4],
      [9,5],
      [3,0,1],
      [8,2],
      [7]
    ]

Company: Google Snapchat Facebook

思路:用BFS来travese树,原因是要从上往下打印。 建2个Queue,第一个queue存node,第二个存对应的距离。往左就是dist-1,往右就是dist+1。用HashMap在相应的距离存下node。<dist,path>
最后将HashMap由key小到大加入list,即从左打到右-TreeMap(or HashMap记录key的min和max)
Complexity: O(N) time O(N) space

关键字:BFS, two queue

public class Solution {
    public List<List<Integer>> verticalOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(root == null)return res;
        Queue<TreeNode> nodes = new LinkedList<TreeNode>();
        Queue<Integer> dist = new LinkedList<Integer>();
        HashMap<Integer,List<Integer>> map = new HashMap <Integer,List<Integer>>();//<dist, path>
        nodes.add(root);
        dist.add(0);
        int min = 0, max = 0;
        while(!nodes.isEmpty()){
            TreeNode cur = nodes.poll();
            int curdis = dist.poll();
            if(!map.containsKey(curdis))map.put(curdis,new ArrayList<Integer>());
            map.get(curdis).add(cur.val);
            if(cur.left != null){
                nodes.add(cur.left);
                dist.add(curdis - 1);
                if(min > curdis - 1){ min = curdis-1;}
            }
            if(cur.right != null){
                nodes.add(cur.right);
                dist.add(curdis + 1);
                if(max < curdis + 1){ max = curdis+1;}
            }
        }
        for(int i = min; i <= max; i++){
            res.add(new ArrayList(map.get(i)));
        }
        return res;
    }
}

2 comments:

  1. 最后几句话好像不用加new ArrayList了吧,map get出来的已经是List了,直接加到res里面就好了吧。

    ReplyDelete
    Replies
    1. 是啊,没必要再加new ArrayList了,直接res.add(map.get(i))就完事了

      Delete