★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-bshlvpwr-ko.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).node
If two nodes are in the same row and column, the order should be from left to right.git
Examples:
Given binary tree [3,9,20,null,null,15,7]
,github
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]
,app
3 / \ 9 20 / \ / \ 4 5 2 7
return its vertical order traversal as:spa
[ [4], [9], [3,5,2], [20], [7] ]
給定二叉樹,返回其節點值的垂直順序遍歷。(即自上而下逐列)。code
若是兩個節點在同一行和同一列中,則順序應該從左到右。htm
實例:blog
給定的二叉樹[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 }