314. Binary Tree Vertical Order Traversal

来源:互联网 发布:素描绘画软件 编辑:程序博客网 时间:2024/06/05 11:57

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. Given binary tree [3,9,20,null,null,15,7],
       3  /\ /  \ 9  20    /\   /  \  15   7

    return its vertical order traversal as:

    [  [9],  [3,15],  [20],  [7]]
  2. Given binary tree [3,9,8,4,0,1,7],
         3    /\   /  \   9   8  /\  /\ /  \/  \ 4  01   7

    return its vertical order traversal as:

    [  [4],  [9],  [3,0,1],  [8],  [7]]
  3. Given binary tree [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5),
         3    /\   /  \   9   8  /\  /\ /  \/  \ 4  01   7    /\   /  \   5   2

    return its vertical order traversal as:

    [  [4],  [9,5],  [3,0,1],  [8,2],  [7]]

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<List<Integer>> verticalOrder(TreeNode root) {        List<List<Integer>> result = new ArrayList<List<Integer>>();          if (root == null) {              return result;          }//层序遍历该树,然后把对应的order加到treemap里面去, treemap就是有树形结构的hashmap        TreeMap<Integer, LinkedList<Integer>> map = new TreeMap<Integer, LinkedList<Integer>>();        Queue<Pair> q = new LinkedList<Pair>();        Pair rootPair = new Pair(0, root);        q.offer(rootPair);        while(!q.isEmpty()){            Pair pair = q.poll();            if(map.containsKey(pair.x)){                map.get(pair.x).add(pair.node.val);            }else{                LinkedList<Integer> list = new LinkedList<Integer>();                list.add(pair.node.val);                map.put(pair.x, list);            }                        if(pair.node.left != null){                Pair left = new Pair(pair.x - 1, pair.node.left);                q.offer(left);            }            if(pair.node.right != null){                Pair right = new Pair(pair.x + 1, pair.node.right);                q.offer(right);            }                    }                for (LinkedList<Integer> a : map.values()) {              result.add(a);          }          return result;     }        public class Pair{        int x;        TreeNode node;        public Pair(int x, TreeNode node){            this.x = x;            this.node = node;        }    }}



0 0
原创粉丝点击