美文网首页
Tree BFS - LC314 Binary Tree Ver

Tree BFS - LC314 Binary Tree Ver

作者: 风烨 | 来源:发表于2017-11-15 05:49 被阅读0次

题目:
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<List<Integer>> verticalOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        Map<Integer, List<Integer>> map = new HashMap();
        int left_margin = 0; 
        Queue<TreeNodePlus> queue = new LinkedList();
        if(root != null) addToQueue(queue, root, 0);
        for(TreeNodePlus nodeplus = queue.poll(); nodeplus != null; nodeplus = queue.poll()){
            List<Integer> 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<TreeNodePlus> 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 Ver

      本文链接:https://www.haomeiwen.com/subject/wyaomxtx.html