Binary Tree Vertical Order Traversal
Posted keepshuatishuati
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Binary Tree Vertical Order Traversal相关的知识,希望对你有一定的参考价值。
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<List<Integer>> verticalOrder(TreeNode root) { 12 List<List<Integer>> result = new ArrayList<>(); 13 if (root == null) { 14 return result; 15 } 16 Map<Integer, List<Integer>> levels = new TreeMap<>(); 17 Queue<TreeNode> nodeQueue = new LinkedList<>(); 18 Queue<Integer> indexQueue = new LinkedList<>(); 19 nodeQueue.offer(root); 20 indexQueue.offer(0); 21 while (!nodeQueue.isEmpty()) { 22 int size = nodeQueue.size(); 23 for (int i = 0; i < size; i++) { 24 TreeNode current = nodeQueue.poll(); 25 int index = indexQueue.poll(); 26 27 if (current.left != null) { 28 nodeQueue.offer(current.left); 29 indexQueue.offer(index - 1); 30 } 31 32 if (current.right != null) { 33 nodeQueue.offer(current.right); 34 indexQueue.offer(index + 1); 35 } 36 37 if (!levels.containsKey(index)) { 38 levels.put(index, new ArrayList<>()); 39 } 40 levels.get(index).add(current.val); 41 } 42 } 43 44 for (Integer i : levels.keySet()) { 45 result.add(new ArrayList<>()); 46 result.get(result.size() - 1).addAll(levels.get(i)); 47 } 48 return result; 49 } 50 }
1. Use TreeMap since it‘s keySet is sorted.
以上是关于Binary Tree Vertical Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章
[Locked] Binary Tree Vertical Order Traversal
314. Binary Tree Vertical Order Traversal
314. Binary Tree Vertical Order Traversal
314. Binary Tree Vertical Order Traversal