Tree BFS - LC314 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.

这道题的目的是把树按列输出,以root为其实点按层遍历,节点的左边列标-1,节点的右边列标+1。然后为了找到起始点好遍历map的keyset,我们用 left_margin 来记录起始位置。

   public  List> verticalOrder(TreeNode root) {
        List> res = new ArrayList<>();
        Map> map = new HashMap();
        int left_margin = 0; 
        Queue queue = new LinkedList();
        if(root != null) addToQueue(queue, root, 0);
        for(TreeNodePlus nodeplus = queue.poll(); nodeplus != null; nodeplus = queue.poll()){
            List list =  map.get(nodeplus.colomn);
            if(list == null){
                list = new ArrayList();
                list.add(nodeplus.node.val);
                map.put(nodeplus.colomn, list);
            } else list.add(nodeplus.node.val);
            
            if(nodeplus.node.left != null){
                int temp = nodeplus.colomn - 1;
                left_margin = Integer.min(left_margin, temp);
                addToQueue(queue, nodeplus.node.left, temp);
            }
            
            if(nodeplus.node.right != null) addToQueue(queue, nodeplus.node.right, nodeplus.colomn + 1);
        }
        if(!map.isEmpty()) for(int i = 0; i < map.size() ; ++i) res.add(map.get(i + left_margin));
        return res;
    }
    
    public void addToQueue(Queue queue, TreeNode node, int colomn){
        TreeNodePlus plus = new TreeNodePlus(node, colomn);
        queue.offer(plus);
    }
    
    public class TreeNodePlus {
        TreeNode node;
        int colomn;
        public TreeNodePlus(TreeNode node, int colomn){
            this.node = node;
            this.colomn = colomn;
        }
    }

你可能感兴趣的:(Tree BFS - LC314 Binary Tree Vertical Order Traversal)