[Swift]LeetCode987. 二叉樹的垂序遍歷 | Vertical Order Traversal of a Binary Tree

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-mwbljwgj-md.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given a binary tree, return the vertical order traversal of its nodes values.node

For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1)and (X+1, Y-1).git

Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes, we report the values of the nodes in order from top to bottom (decreasing Y coordinates).github

If two nodes have the same position, then the value of the node that is reported first is the value that is smaller.微信

Return an list of non-empty reports in order of X coordinate.  Every report will have a list of values of nodes.app

Example 1:spa

Input: [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]] Explanation: Without loss of generality, we can assume the root node is at position (0, 0): Then, the node with value 9 occurs at position (-1, -1); The nodes with values 3 and 15 occur at positions (0, 0) and (0, -2); The node with value 20 occurs at position (1, -1); The node with value 7 occurs at position (2, -2). 

Example 2:code

Input: [1,2,3,4,5,6,7]
Output: [[4],[2],[1,5,6],[3],[7]] Explanation: The node with value 5 and the node with value 6 have the same position according to the given scheme. However, in the report "[1,5,6]", the node value of 5 comes first since 5 is smaller than 6.

Note:htm

  1. The tree will have between 1 and 1000 nodes.
  2. Each node's value will be between 0 and 1000.

給定二叉樹,按垂序遍歷返回其結點值。blog

對位於 (X, Y) 的每一個結點而言,其左右子結點分別位於 (X-1, Y-1) 和 (X+1, Y-1)

把一條垂線從 X = -infinity 移動到 X = +infinity ,每當該垂線與結點接觸時,咱們按從上到下的順序報告結點的值( Y 座標遞減)。

若是兩個結點位置相同,則首先報告的結點值較小。

按 X 座標順序返回非空報告的列表。每一個報告都有一個結點值列表。

示例 1:

輸入:[3,9,20,null,null,15,7]
輸出:[[9],[3,15],[20],[7]]
解釋: 
在不喪失其廣泛性的狀況下,咱們能夠假設根結點位於 (0, 0):
而後,值爲 9 的結點出如今 (-1, -1);
值爲 3 和 15 的兩個結點分別出如今 (0, 0) 和 (0, -2);
值爲 20 的結點出如今 (1, -1);
值爲 7 的結點出如今 (2, -2)。

示例 2:

輸入:[1,2,3,4,5,6,7]
輸出:[[4],[2],[1,5,6],[3],[7]]
解釋:
根據給定的方案,值爲 5 和 6 的兩個結點出如今同一位置。
然而,在報告 "[1,5,6]" 中,結點值 5 排在前面,由於 5 小於 6。

提示:

  1. 樹的結點數介於 1 和 1000 之間。
  2. 每一個結點值介於 0 和 1000 之間。

16ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     var map = [Int: [(Int, Int)]]()
16     func verticalTraversal(_ root: TreeNode?) -> [[Int]] {
17         if root == nil {
18             return []
19         }
20         map[0] = [(root!.val, 0)]
21         traversTree(root!.left, true, 0, -1)
22         traversTree(root!.right, false, 0, -1)
23         var ans = [[Int]]()
24         for k in map.keys.sorted() {            
25             let sortedTuple = map[k]!.sorted {($0, $1)
26                 if $0.1 > $1.1 { return true }
27                 if $0.1 == $1.1 { return $0.0 < $1.0 }
28                 return false
29             }
30             let arr = sortedTuple.map {$0.0}
31             ans.append(arr)
32         }
33         return ans
34     }
35 
36     func traversTree(_ node: TreeNode?, _ left: Bool, _ v: Int, _ vv: Int) {
37         if node != nil {
38             let k = left ? v-1 : v+1
39             var arr = map[k] ?? [(Int, Int)]()
40             arr.append((node!.val, vv))
41             map[k] = arr
42             traversTree(node!.left, true, k, vv-1)
43             traversTree(node!.right, false, k, vv-1)
44         }
45     }
46 }

Runtime: 20 ms
Memory Usage: 4.1 MB
 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     var hi:[[Int]] = [[Int]]()
16     func verticalTraversal(_ root: TreeNode?) -> [[Int]] {
17         dfs(root, 0, 0)
18         hi.sort(by:sortArray)
19         var ret:[[Int]] = [[Int]]()
20         var i:Int = 0
21         while(i < hi.count)
22         {
23             var j:Int = i
24             while(j < hi.count && hi[j][1] == hi[i][1])
25             {
26                 j += 1
27             }
28             var item:[Int] = [Int]()
29             for k in i..<j
30             {
31                 item.append(hi[k][0])
32             }
33             ret.append(item)
34             i = j
35         }
36         return ret
37     }
38     
39     func sortArray(_ a:[Int],_ b:[Int]) -> Bool
40     {
41         if a[1] != b[1] {return a[1] < b[1]}
42         if a[2] != b[2] {return a[2] > b[2]}
43         return a[0] < b[0]
44     }
45     
46     func dfs(_ cur: TreeNode?,_ x:Int,_ y:Int)
47     {
48         if cur == nil {return}
49         hi.append([cur!.val,x,y])
50         dfs(cur!.left, x-1, y-1)
51         dfs(cur!.right, x+1, y-1)
52     }
53 }

24ms 
 1 class Solution {
 2     func verticalTraversal(_ root: TreeNode?) -> [[Int]] {
 3         var res: [[Int]] = []
 4 
 5         var dict: [Int: [(Int, [Int])]] = [:]
 6         
 7         func tra(_ node: TreeNode?, _ x: Int, y: Int) {
 8             guard let node = node else {
 9                 return
10             }
11 
12             if dict[x] == nil {
13                 dict[x] = [(y, [node.val])]
14             } else {
15                 var sameY = false
16                 
17                 for (index, (yVal, nodeVal)) in dict[x]!.enumerated() {
18                     if yVal == y {
19                         sameY = true
20                         
21                         var newVal = nodeVal
22                         newVal.append(node.val)
23                         
24                         dict[x]![index].1 = newVal.sorted()
25                     }
26                 }
27                 
28                 if sameY == false {
29                     dict[x]!.append((y, [node.val]))
30                 }
31             }
32             
33             tra(node.left, x - 1, y: y - 1)
34             tra(node.right, x + 1, y: y - 1)
35         }
36         
37         tra(root, 0, y: 0)
38         
39         let sortedDict = dict.sorted(by: {$0.key < $1.key})
40         
41         for dict in sortedDict {
42             var vals: [Int] = []
43             
44             for (_, val) in dict.value.sorted(by: { $0.0 > $1.0 }) {
45                 vals += val
46             }
47             
48             res.append(vals)
49         }
50         
51         return res
52     }
53 }
相關文章
相關標籤/搜索