314. 二叉树的垂直遍历

 

 

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());
    }
}

 

posted @ 2020-07-14 19:23  Sexyomaru  阅读(95)  评论(0编辑  收藏  举报