Binary Tree Vertical Order Traversal

来源:互联网 发布:php固定资产管理系统 编辑:程序博客网 时间:2024/05/20 18:54

en 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]]



最近按照tag刷题。下个学期校招应该有facebook,希望能有机会面个试。

这道题的思路是建立hashmap, 竖着来看每一个节点对应一个index, 建立的时候记录下它位于哪一层就好。这个父亲跟左右孩子的Index的关系s是: parent Index = left child Index +1 = right child index -1。 这道题还要保序,感觉dfs就不太合适了。用了bfs做。

代码:

public class Solution {    class Wrap{    TreeNode node;    int key;    public Wrap(TreeNode node, int key) {        this.node = node;        this.key = key;    }}    public List<List<Integer>> verticalOrder(TreeNode root) {        List<List<Integer>> result = new ArrayList<>();        if(root == null) return result;        Queue<Wrap> queue = new LinkedList<>();        TreeMap<Integer, List<Integer>> map = new TreeMap<>();        queue.offer(new Wrap(root, 0));        while(!queue.isEmpty()){            Wrap node = queue.poll();            if(!map.containsKey(node.key)){               map.put(node.key, new ArrayList<>());            }            map.get(node.key).add(node.node.val);            if(node.node.left != null){                queue.offer(new Wrap(node.node.left, node.key-1));            }            if(node.node.right != null){                queue.offer(new Wrap(node.node.right, node.key+1));            }        }        for(Map.Entry<Integer, List<Integer>> entry: map.entrySet()){            result.add(entry.getValue());        }        return result;    }


0 0
原创粉丝点击