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<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;
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,355评论 19 139
  • 94. Binary Tree Inorder Traversal 中序 inorder:左节点->根节点->右节...
    Morphiaaa阅读 3,736评论 0 0
  • 1〗 “她是个‘不正常的孩子’。” 提到她的时候妈妈这么说,叮嘱小侄子不要去靠近她,不要和她在一起玩耍,不要把零食...
    如烟鱼阅读 3,262评论 2 2
  • 第一次来丽江。 第一次一个人,独自。 下了飞机,云淡风轻。我坐在机场大巴上,徐徐前行。其实我是来短期支教的。 车载...
    睫毛弯弯ww阅读 3,555评论 0 0