码迷,mamicode.com
首页 > 其他好文 > 详细

314. Binary Tree Vertical Order Traversal

时间:2018-08-17 00:37:02      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:node   new   linked   arraylist   order   ini   root   list   color   

314. Binary Tree Vertical Order Traversal

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    class Pair{
        TreeNode node;
        Integer pos;
        
        public Pair(TreeNode node, Integer pos){
            this.node = node;
            this.pos = pos;
        }
    }
    public List<List<Integer>> verticalOrder(TreeNode root) {
        HashMap<Integer, List<Integer>> map = new HashMap<>();
        List<List<Integer>> result = new ArrayList<>();
        if(root == null){
            return result;
        }
        
        Queue<Pair> queue = new LinkedList<>();
        Integer max = 0;
        Integer min = 0;
        
        queue.offer(new Pair(root, 0));
        while(!queue.isEmpty()){
            Pair cur = queue.poll();
            Integer curPos = cur.pos;
            TreeNode curNode = cur.node;
            
            if(!map.containsKey(curPos)){
                map.put(curPos, new ArrayList<>());
            }
            map.get(curPos).add(curNode.val);
            
            if(curNode.left != null){
                min = Math.min(min, curPos - 1);
                queue.offer(new Pair(curNode.left, curPos - 1));
            }
            
            if(curNode.right != null){
                max = Math.max(max, curPos + 1);
                queue.offer(new Pair(curNode.right, curPos + 1));
            }
        }
        for(int i = min; i <= max; i++){
            
            result.add(map.get(i));
        }
        return result;
    }
}

 

314. Binary Tree Vertical Order Traversal

标签:node   new   linked   arraylist   order   ini   root   list   color   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9490889.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!