为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode314. 二叉树的竖直遍历 $ Binary Tree Vertical Order Traversal

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10706508.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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

    3
   / \
  9  20
    /  \
   15   7

return its vertical order traversal as:

[
  [9],
  [3,15],
  [20],
  [7]
]

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

     3
   /   \
  9    20
 / \   / \
4   5 2   7

return its vertical order traversal as:

[
  [4],
  [9],
  [3,5,2],
  [20],
  [7]
]

给定二叉树,返回其节点值的垂直顺序遍历。(即自上而下逐列)。

 

如果两个节点在同一行和同一列中,则顺序应该从左到右。

 

实例:

给定的二叉树[3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其垂直顺序遍历为:

[
  [9],
  [3,15],
  [20],
  [7]
]

给定二叉树

[3,9,20,4,5,2,7],

     3
   /   \
  9    20
 / \   / \
4   5 2   7

返回其垂直顺序遍历为:

[
  [4],
  [9],
  [3,5,2],
  [20],
  [7]
]

Solution:
 1 public class TreeNode {
 2     public var val: Int
 3     public var left: TreeNode?
 4     public var right: TreeNode?
 5     public init(_ val: Int) {
 6         self.val = val
 7         self.left = nil
 8         self.right = nil
 9     }
10 }
11 
12 class Solution {
13     func verticalOrder(_ root: TreeNode?) ->[[Int]] {
14         var res:[[Int]] = [[Int]]()
15         if root == nil {return res}
16         var m:[Int:[Int]] = [Int:[Int]]()
17         var q:[(Int,TreeNode?)] = [(Int,TreeNode?)]()
18         q.append((0, root))
19         while(!q.isEmpty)
20         {
21             var a:(Int,TreeNode?) = q.first!
22             q.popLast()
23             m[a.0,default:[Int]()].append(a.1!.val)
24             if a.1?.left != nil
25             {
26                 q.append((a.0 - 1, a.1!.left))
27             }
28             if a.1?.right != nil
29             {
30                 q.append((a.0 + 1, a.1!.right))
31             }
32         }
33         for a in m
34         {
35             res.append(a.1)
36         }
37         return res             
38     }
39 }

 

posted @ 2019-04-14 19:22  为敢技术  阅读(259)  评论(0编辑  收藏  举报