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

  1. 3
  2. / \
  3. 9 20
  4. / \
  5. 15 7

return its vertical order traversal as:

  1. [
  2. [9],
  3. [3,15],
  4. [20],
  5. [7]
  6. ]

Given binary tree [3,9,20,4,5,2,7],

  1. _3_
  2. / \
  3. 9 20
  4. / \ / \
  5. 4 5 2 7

return its vertical order traversal as:

  1. [
  2. [4],
  3. [9],
  4. [3,5,2],
  5. [20],
  6. [7]
  7. ]

二叉树的垂直遍历。

解法:如果一个node的column是 i,那么它的左子树column就是i - 1,右子树column就是i + 1。建立一个TreeColumnNode,包含一个TreeNode,以及一个column value,然后用level order traversal进行计算,并用一个HashMap保存column value以及相同value的点。也要设置一个min column value和一个max column value,方便最后按照从小到大顺序获取hashmap里的值输出。

Java:

  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. private class TreeColumnNode{
  12. public TreeNode treeNode;
  13. int col;
  14. public TreeColumnNode(TreeNode node, int col) {
  15. this.treeNode = node;
  16. this.col = col;
  17. }
  18. }
  19.  
  20. public List<List<Integer>> verticalOrder(TreeNode root) {
  21. List<List<Integer>> res = new ArrayList<>();
  22. if(root == null) {
  23. return res;
  24. }
  25. Queue<TreeColumnNode> queue = new LinkedList<>();
  26. Map<Integer, List<Integer>> map = new HashMap<>();
  27. queue.offer(new TreeColumnNode(root, 0));
  28. int curLevel = 1;
  29. int nextLevel = 0;
  30. int min = 0;
  31. int max = 0;
  32.  
  33. while(!queue.isEmpty()) {
  34. TreeColumnNode node = queue.poll();
  35. if(map.containsKey(node.col)) {
  36. map.get(node.col).add(node.treeNode.val);
  37. } else {
  38. map.put(node.col, new ArrayList<Integer>(Arrays.asList(node.treeNode.val)));
  39. }
  40. curLevel--;
  41.  
  42. if(node.treeNode.left != null) {
  43. queue.offer(new TreeColumnNode(node.treeNode.left, node.col - 1));
  44. nextLevel++;
  45. min = Math.min(node.col - 1, min);
  46. }
  47. if(node.treeNode.right != null) {
  48. queue.offer(new TreeColumnNode(node.treeNode.right, node.col + 1));
  49. nextLevel++;
  50. max = Math.max(node.col + 1, max);
  51. }
  52. if(curLevel == 0) {
  53. curLevel = nextLevel;
  54. nextLevel = 0;
  55. }
  56. }
  57.  
  58. for(int i = min; i <= max; i++) {
  59. res.add(map.get(i));
  60. }
  61.  
  62. return res;
  63. }
  64. }

Java:

  1. class Solution {
  2. public List<List<Integer>> verticalOrder(TreeNode root) {
  3. List<List<Integer>> result = new ArrayList<List<Integer>>();
  4. if(root==null)
  5. return result;
  6.  
  7. // level and list
  8. HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
  9.  
  10. LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
  11. LinkedList<Integer> level = new LinkedList<Integer>();
  12.  
  13. queue.offer(root);
  14. level.offer(0);
  15.  
  16. int minLevel=0;
  17. int maxLevel=0;
  18.  
  19. while(!queue.isEmpty()){
  20. TreeNode p = queue.poll();
  21. int l = level.poll();
  22.  
  23. //track min and max levels
  24. minLevel=Math.min(minLevel, l);
  25. maxLevel=Math.max(maxLevel, l);
  26.  
  27. if(map.containsKey(l)){
  28. map.get(l).add(p.val);
  29. }else{
  30. ArrayList<Integer> list = new ArrayList<Integer>();
  31. list.add(p.val);
  32. map.put(l, list);
  33. }
  34.  
  35. if(p.left!=null){
  36. queue.offer(p.left);
  37. level.offer(l-1);
  38. }
  39.  
  40. if(p.right!=null){
  41. queue.offer(p.right);
  42. level.offer(l+1);
  43. }
  44. }
  45.  
  46. for(int i=minLevel; i<=maxLevel; i++){
  47. if(map.containsKey(i)){
  48. result.add(map.get(i));
  49. }
  50. }
  51.  
  52. return result;
  53. }
  54. }

Python:  BFS + hash solution.

  1. class Solution(object):
  2. def verticalOrder(self, root):
  3. """
  4. :type root: TreeNode
  5. :rtype: List[List[int]]
  6. """
  7. cols = collections.defaultdict(list)
  8. queue = [(root, 0)]
  9. for node, i in queue:
  10. if node:
  11. cols[i].append(node.val)
  12. queue += (node.left, i - 1), (node.right, i + 1)
  13. return [cols[i] for i in xrange(min(cols.keys()), max(cols.keys()) + 1)] \
  14. if cols else []

C++:

  1. class Solution {
  2. public:
  3. vector<vector<int>> verticalOrder(TreeNode* root) {
  4. vector<vector<int>> res;
  5. if (!root) return res;
  6. map<int, vector<int>> m;
  7. queue<pair<int, TreeNode*>> q;
  8. q.push({0, root});
  9. while (!q.empty()) {
  10. auto a = q.front(); q.pop();
  11. m[a.first].push_back(a.second->val);
  12. if (a.second->left) q.push({a.first - 1, a.second->left});
  13. if (a.second->right) q.push({a.first + 1, a.second->right});
  14. }
  15. for (auto a : m) {
  16. res.push_back(a.second);
  17. }
  18. return res;
  19. }
  20. };
  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. vector<vector<int>> verticalOrder(TreeNode* root) {
  13. unordered_map<int, vector<int>> cols;
  14. vector<pair<TreeNode *, int>> queue{{root, 0}};
  15. for (int i = 0; i < queue.size(); ++i) {
  16. TreeNode *node;
  17. int j;
  18. tie(node, j) = queue[i];
  19. if (node) {
  20. cols[j].emplace_back(node->val);
  21. queue.push_back({node->left, j - 1});
  22. queue.push_back({node->right, j + 1});
  23. }
  24. }
  25. int min_idx = numeric_limits<int>::max(),
  26. max_idx = numeric_limits<int>::min();
  27. for (const auto& kvp : cols) {
  28. min_idx = min(min_idx, kvp.first);
  29. max_idx = max(max_idx, kvp.first);
  30. }
  31. vector<vector<int>> res;
  32. for (int i = min_idx; !cols.empty() && i <= max_idx; ++i) {
  33. res.emplace_back(move(cols[i]));
  34. }
  35. return res;
  36. }
  37. };

  

All LeetCode Questions List 题目汇总

[LeetCode] 314. Binary Tree Vertical Order Traversal 二叉树的垂直遍历的更多相关文章

  1. [LeetCode] 314. Binary Tree Vertical Order Traversal 二叉树的竖直遍历

    Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bott ...

  2. [leetcode]314. Binary Tree Vertical Order Traversal二叉树垂直遍历

    Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bott ...

  3. LeetCode 314. Binary Tree Vertical Order Traversal

    原题链接在这里:https://leetcode.com/problems/binary-tree-vertical-order-traversal/ 题目: Given a binary tree, ...

  4. leetcode 题解:Binary Tree Level Order Traversal (二叉树的层序遍历)

    题目: Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to ri ...

  5. LeetCode 102. Binary Tree Level Order Traversal 二叉树的层次遍历 C++

    Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, ...

  6. 【LeetCode】Binary Tree Level Order Traversal(二叉树的层次遍历)

    这道题是LeetCode里的第102道题. 题目要求: 给定一个二叉树,返回其按层次遍历的节点值. (即逐层地,从左到右访问所有节点). 例如: 给定二叉树: [3,9,20,null,null,15 ...

  7. leetcode 102.Binary Tree Level Order Traversal 二叉树的层次遍历

    基础为用队列实现二叉树的层序遍历,本题变体是分别存储某一层的元素,那么只要知道,每一层的元素都是上一层的子元素,那么只要在while循环里面加个for循环,将当前队列的值(即本层元素)全部访问后再执行 ...

  8. [LeetCode] 102. Binary Tree Level Order Traversal 二叉树层序遍历

    Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, ...

  9. [LeetCode] Binary Tree Vertical Order Traversal 二叉树的竖直遍历

    Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bott ...

随机推荐

  1. PAT甲级1008水题飘过

    题目分析:上去下来到达的时间和数量 #include<iostream> using namespace std; ]; int main(){ int n; while(scanf(&q ...

  2. P2606 [ZJOI2010]排列计数

    P2606 [ZJOI2010]排列计数 因为每个结点至多有一个前驱,所以我们可以发现这是一个二叉树.现在我们要求的就是以1为根的二叉树中,有多少种情况,满足小根堆的性质. 设\(f(i)\)表示以\ ...

  3. Java动态代理演变之路

    1.什么是代理? 代理,英文成文Proxy.意思是你不用去做,别人代替你去处理.比如有人想找明星周董去唱歌,他需要做签约.讨论.唱歌和付款等等过程,但真正周董擅长的事情是唱歌,其他的事情可以交代给他的 ...

  4. 代码编辑器与IDE(集成开发环境)

    编辑器就是轻量级的只用于编辑代码: nodepad++, sublime, ...... IDE就是包含很多例如调试, 编译,UI界面的功能更为完善的软件: Pycharm(python用的多), V ...

  5. luoguP1120小木棍(POJ - 1011 )

     题意: 乔治有一些同样长的小木棍,他把这些木棍随意砍成几段,直到每段的长都不超过50,个数不超过65. 现在,他想把小木棍拼接成原来的样子,但是却忘记了自己开始时有多少根木棍和它们的长度. 给出每段 ...

  6. centos7中,mysql连接报错:1130 - Host ‘118.111.111.111’ is not allowed to connect to this MariaDB server

    客户端连接报错 这个问题是因为用户在数据库服务器中的mysql数据库中的user的表中没有权限. 解决步骤 1.连接服务器: mysql -u root -p 2.看当前所有数据库:show data ...

  7. php过滤敏感词

    <?php /**  * 敏感词过滤工具类  * 使用方法  * echo FilterTools::filterContent("你妈的我操一色狼杂种二山食物"," ...

  8. python字符的表示格式

    %% 百分号标记 #就是输出一个% %c 字符及其ASCII码%s 字符串%d 有符号整数(十进制)%u 无符号整数(十进制)%o 无符号整数(八进制)%x 无符号整数(十六进制)%X 无符号整数(十 ...

  9. C++指针的一些问题

    用变量a给出下面的定义: a)一个整形数(An integer) b)一个指向整形数的指针 c)一个指向指针的指针,它指向的指针指向一个整形数 d)一个有十个整形数的数组 e)一个有十个指针的数组,该 ...

  10. oracle 按每天,每周,每月,每季度,每年查询统计数据

    oracle 按每天,每周,每月,每季度,每年查询统计数据 //按天统计 select count(dataid) as 每天操作数量, sum() from tablename group by t ...