在线时间:8:00-16:00
迪恩网络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: 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 return its vertical order traversal as: [ [4], [9], [3,5,2], [20], [7] ] 给定二叉树,返回其节点值的垂直顺序遍历。(即自上而下逐列)。
如果两个节点在同一行和同一列中,则顺序应该从左到右。
实例: 给定的二叉树 3 / \ 9 20 / \ 15 7 返回其垂直顺序遍历为: [ [9], [3,15], [20], [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 }
|
请发表评论