• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

[Swift]LeetCode863.二叉树中所有距离为K的结点|AllNodesDistanceKinBinaryTree ...

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

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

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

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

We are given a binary tree (with root node root), a targetnode, and an integer value K.

Return a list of the values of all nodes that have a distance Kfrom the target node.  The answer can be returned in any order.

Example 1:

Input: root = 2

Output: [7,4,1]

Explanation: 
The nodes that are a distance 2 from the target node (with value 5)
have values 7, 4, and 1.



Note that the inputs "root" and "target" are actually TreeNodes.
The descriptions of the inputs above are just serializations of these objects.

Note:

  1. The given tree is non-empty.
  2. Each node in the tree has unique values 0 <= node.val <= 500.
  3. The target node is a node in the tree.
  4. 0 <= K <= 1000.

给定一个二叉树(具有根结点 root), 一个目标结点 target ,和一个整数值 K 。

返回到目标结点 target 距离为 K 的所有结点的值的列表。 答案可以以任何顺序返回。

示例 1:

输入:root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2

输出:[7,4,1]

解释:
所求结点为与目标结点(值为 5)距离为 2 的结点,
值分别为 7,4,以及 1

注意,输入的 "root" 和 "target" 实际上是树上的结点。
上面的输入仅仅是对这些对象进行了序列化描述。

提示:

  1. 给定的树是非空的,且最多有 K 个结点。
  2. 树上的每个结点都具有唯一的值 0 <= node.val <= 500 。
  3. 目标结点 target 是树上的结点。
  4. 0 <= K <= 1000.

16ms

 

 1 class Solution {
 2     func distanceK(_ root: TreeNode?, _ target: TreeNode?, _ K: Int) -> [Int] {
 3         guard let root = root else { return [] }
 4         guard let target = target else { return [] }
 5         
 6         let result = dfs(root, 0, target: target)
 7         let path = result.paths.reversed()
 8         let level = result.level
 9         
10         var results = [Int]()
11         var node = root
12         
13         for (currentLevel, step) in path.enumerated() {
14             let t = K - (level - currentLevel) - 1
15             if t == -1 {
16                 results.append(node.val)
17             }
18             if step {
19                 if let right = node.right, t >= 0 {
20                     results += bfs(right, t)
21                 }
22                 node = node.left!
23             } else {
24                 if let left = node.left, t >= 0 {
25                     results += bfs(left, t)
26                 }
27                 node = node.right!
28             }
29         }
30         
31         results += bfs(node, K)
32         
33         return results
34     }
35     
36     func bfs(_ root: TreeNode, _ targetLevel: Int) -> [Int] {
37         var queue = [root]
38         var level = 0
39         
40         while !queue.isEmpty && level < targetLevel {
41             var nextQueue = [TreeNode]()
42             
43             for node in queue {
44                 if let n = node.left {
45                     nextQueue.append(n)
46                 }
47                 
48                 if let n = node.right {
49                     nextQueue.append(n)
50                 }
51             }
52             
53             queue = nextQueue
54             level += 1
55         }
56         
57         if level == targetLevel {
58             return queue.map { $0.val }
59         } else {
60             return []
61         }
62     }
63     
64     func dfs(_ root: TreeNode, _ level: Int, target: TreeNode) -> (paths: [Bool], level: Int) {
65         if root.left === target {
66             return ([true], level + 1)
67         } else if root.right === target {
68             return ([false], level + 1)
69         }
70         
71         if let left = root.left {
72             let result = dfs(left, level + 1, target: target)
73             if result.level > 0 {
74                 return (result.paths + [true], result.level)
75             }
76         }
77         
78         if let right = root.right {
79             let result = dfs(right, level + 1, target: target)
80             if result.level > 0 {
81                 return (result.paths + [false], result.level)
82             }
83         }
84         
85         return ([], -1)
86     }
87 }

24ms

 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     func distanceK(_ root: TreeNode?, _ target: TreeNode?, _ K: Int) -> [Int] {
16         guard let root = root, let target = target else { return [] }
17         guard K != 0 else { return [target.val] }
18         
19         var graph: [Int : [Int]] = [:]
20         toGraph(&graph, parent: nil, child: root)
21         var distances: [Int : Int] = [:]
22         distances[target.val] = 0
23         var queue: [Int] = [target.val]
24         var status: [Int : Bool] = [:]
25         var result: [Int] = []
26      
27         while !queue.isEmpty {
28             let current = queue.removeFirst()
29             status[current] = true
30             guard let connectedV = graph[current] else { break }
31             for v in connectedV {
32                 guard (status[v] ?? false) == false else { continue }
33                 queue.append(v)
34                 let distanceV = distances[current]! + 1
35                 distances[v] = distanceV
36                 if distanceV == K {
37                     result.append(v)
38                 }
39             }
40         }
41         
42         return result
43     }
44     
45     func toGraph(_ result: inout [Int : [Int]], parent: TreeNode?, child: TreeNode) {
46         if let parent = parent {
47             if result[child.val] == nil {
48                 result[child.val] = [parent.val]
49             }else{
50                 result[child.val]?.append(parent.val)
51             }
52             if result[parent.val] == nil {
53                 result[parent.val] = [child.val]
54             }else{
55                 result[parent.val]?.append(child.val)
56             }
57         }
58         if let left = child.left {
59             toGraph(&result, parent: child, child: left)
60         }
61         if let right = child.right {
62             toGraph(&result, parent: child, child: right)
63         }
64     }
65 }

32ms

  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     func distanceK(_ root: TreeNode?, _ target: TreeNode?, _ K: Int) -> [Int] {
 16         guard let root = root else {
 17             return []
 18         }
 19         
 20         guard K != 0 else {
 21             return [target!.val]
 22         }
 23         
 24         let graph = Graph<Int>()
 25         inorderTraversal(root) {
 26             node in 
 27             let source = graph.createVertex(node.val)
 28             if node.left != nil {
 29                 let destination = graph.createVertex(node.left!.val)
 30                 graph.addUndirectedEdge(between: source, to: destination)
 31             }
 32             
 33             if node.right != nil {
 34                 let destination = graph.createVertex(node.right!.val)
 35                 graph.addUndirectedEdge(between: source, to: destination)
 36             }
 37         }
 38         return breathFirstTraversal(graph, Vertex(target!.val), K)
 39     }
 40 
 41 }
 42 
 43 func breathFirstTraversal<T: Hashable>(_ graph: Graph<T>, 
 44                                        _ source: Vertex<T>, 
 45                                        _ k: Int     
 46                                       ) -> [T] {
 47     var discovered: Set<Vertex<T>> = [source]
 48     var stack: [Vertex<T>] = [source]
 49     var k = k 
 50     while k > 0 {
 51         var tmp: [Vertex<T>] = []
 52         while let source = stack.popLast() {
 53             for edge in graph.edges(of: source) {
 54                 let destination = edge.destination 
 55                 if !discovered.contains(destination) {
 56                     tmp.append(destination)
 57                     discovered.insert(destination)
 58                 }
 59             }
 60         }
 61         k -= 1 
 62         if k == 0 {
 63             return tmp.map { $0.val }
 64         }
 65         if tmp.isEmpty { break }
 66         stack = tmp
 67     }
 68     
 69     return []
 70 }
 71 
 72 func inorderTraversal(_ root: TreeNode?, _ visit: (TreeNode) -> Void) {
 73     guard let root = root else {
 74         return 
 75     }
 76     inorderTraversal(root.left, visit)
 77     visit(root)
 78     inorderTraversal(root.right, visit)
 79 }
 80 
 81 struct Vertex<T: Hashable> : Hashable {
 82     public var val: T 
 83     public init(_ val: T) {
 84         self.val = val 
 85     }
 86     
 87     public var hashValue: Int {
 88         return val.hashValue 
 89     }
 90     
 91     public static func ==(lhs: Vertex<T>, rhs: Vertex<T>) -> Bool {
 92         return lhs.val == rhs.val
 93     }
 94 }
 95 
 96 struct Edge<T: Hashable> {
 97     public let source: Vertex<T>
 98     public let destination: Vertex<T>
 99     public let weight: Double? 
100 
101     public init(source: Vertex<T>, destination: Vertex<T>, weight: Double? = nil) {
102         self.source = source 
103         self.destination = destination 
104         self.weight = weight 
105     }
106 }
107 
108 class Graph<T: Hashable> {
109     public var vertice: [Vertex<T>] = []
110     private var adjacencyList: [Vertex<T>: [Edge<T>]] = [:]
111     
112     public func createVertex(_ val: T) -> Vertex<T> {
113         let source = Vertex(val)
114         if adjacencyList[source] == nil {
115             adjacencyList[source] = []
116             vertice.append(source)
117         }
118         return source
119     }
120     
121     public func addDirectedEdge(from source: Vertex<T>, 
122                                 to destination: Vertex<T>,
123                                 weight: Double? = nil 
124                                ) {
125         let edge = Edge(source: source, destination: destination, weight: weight)
126         adjacencyList[source]?.append(edge)
127     }
128     
129     public func addUndirectedEdge(between source: Vertex<T>, 
130                                   to destination: Vertex<T>, 
131                                   weight: Double? = nil
132                                  ) {
133         addDirectedEdge(from: source, to: destination, weight: weight)
134         addDirectedEdge(from: destination, to: source, weight: weight)
135     }
136     
137     public func edges(of source: Vertex<T>) -> [Edge<T>] {
138         return adjacencyList[source] ?? []
139     }
140     
141     public func weight(from source: Vertex<T>, to destination: Vertex<T>) -> Double? {
142         return adjacencyList[source]?.first{ $0.destination == destination }?.weight
143     }
144 }

Runtime: 32 ms
Memory Usage: 19.2 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 map:[(TreeNode,String)] = [(TreeNode,String)]()
16     var path:String = String()
17     func distanceK(_ root: TreeNode?, _ target: TreeNode?, _ K: Int) -> [Int] {
18         var list:[Int] = [Int]()
19         getNodeDist(root,target,"")
20         var i:Int = 0
21         for ele in map
22         {
23             var s:String = ele.1
24             var i:Int = 0
25             var arrS:[Character] = Array(s)
26             var arrP:[Character] = Array(path)
27             while(i<s.count && i<path.count && arrS[i] == arrP[i])
28             {
29                 i += 1
30             }
31             if s.count - i + path.count - i == K
32             {
33                 list.append(ele.0.val)
34             }
35         }
36         return list        
37     }
38 
39     func getNodeDist(_ root: TreeNode?,_ target: TreeNode?,_ p:String)
40     {
41         if root != nil
42         {
43             path = root!.val == target!.val ? p : path
44             map.append((root!, p))
45             getNodeDist(root?.left,target,p+"0")
46             getNodeDist(root?.right,target,p+"1")
47         }
48     }    
49 }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Swift本地推送通知UILocalNotification发布时间:2022-07-13
下一篇:
[Swift]LeetCode1021.删除最外层的括号|RemoveOutermostParentheses发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap