314. Binary Tree Vertical Order Traversal
Posted tobeabetterpig
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了314. Binary Tree Vertical Order Traversal相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
314. Binary Tree Vertical Order Traversal
314. Binary Tree Vertical Order Traversal
Leetcode 314. Binary Tree Vertical Order Traversal
Leetcode 314: Binary Tree Vertical Order Traversal