[LeetCode] 314. Binary Tree Vertical Order Traversal

发布时间:2019-06-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[LeetCode] 314. Binary Tree Vertical Order Traversal脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Problem

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:

Input: [3,9,20,null,null,15,7]

  3
  /
 /  
 9  20
    /
   /  
  15   7 

Output:

[
  [9],
  [3,15],
  [20],
  [7]
]

Solution

class Solution {
    public List<List<Integer>> verticalOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        
        //store <column, node list>
        Map<Integer, List<Integer>> map = new HashMap<>();
        //store min col, max col
        int min = 0, max = 0;
        
        //store TreeNode
        Queue<TreeNode> queue = new LinkedList<>();
        //store column number
        Queue<Integer> colqueue = new LinkedList<>();
        
        //queue's elements are mapped to colqueue's elements
        //e.g. root's column number is 0
        queue.offer(root);
        colqueue.offer(0);
        
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            int col = colqueue.poll();
            
            if (!map.containsKey(col)) {
                map.put(col, new ArrayList<Integer>());
            }
            map.get(col).add(node.val);
            
            if (node.left != null) {
                queue.offer(node.left);
                colqueue.offer(col-1);
                min = Math.min(min, col-1);
            }
            
            if (node.right != null) {
                queue.offer(node.right);
                colqueue.offer(col+1);
                max = Math.max(max, col+1);
            }
        }
        
        for (int i = min; i <= max; i++) {
            res.add(map.get(i));
        }
        
        return res;
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的[LeetCode] 314. Binary Tree Vertical Order Traversal全部内容,希望文章能够帮你解决[LeetCode] 314. Binary Tree Vertical Order Traversal所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: