首页 > 其他 > 详细

314. 二叉树的垂直遍历

时间:2020-07-14 20:01:45      阅读:65      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 

class Solution {
    public List<List<Integer>> verticalOrder(TreeNode root) {
        if(root == null) return new ArrayList<>();
        Map<Integer,List<Integer>> map = new TreeMap<>(); // 存放按位置排序的list
        Map<TreeNode,Integer> posMap = new HashMap<>(); // 存放节点的位置
        posMap.put(root,0);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()) {  // 层序遍历
            TreeNode node = queue.poll();
            int i = posMap.get(node);
            map.computeIfAbsent(i,k->new ArrayList<>()).add(node.val);
            if(node.left != null) {
                queue.add(node.left);
                posMap.put(node.left,i-1);
            }
            if(node.right != null) {
                queue.add(node.right);
                posMap.put(node.right,i+1);
            }
        }
        return new ArrayList<>(map.values());
    }
}

 

314. 二叉树的垂直遍历

原文:https://www.cnblogs.com/yonezu/p/13301059.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!