★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-rtzhgnld-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
We are given a binary tree (with root node root
), a target
node, and an integer value K
.node
Return a list of the values of all nodes that have a distance K
from the target
node. The answer can be returned in any order.git
Example 1:github
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 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:微信
0 <= node.val <= 500
.target
node is a node in the tree.0 <= K <= 1000
.給定一個二叉樹(具備根結點 root
), 一個目標結點 target
,和一個整數值 K
。app
返回到目標結點 target
距離爲 K
的全部結點的值的列表。 答案能夠以任何順序返回。spa
示例 1:code
輸入: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" 其實是樹上的結點。 上面的輸入僅僅是對這些對象進行了序列化描述。
提示:htm
K
個結點。0 <= node.val <= 500
。target
是樹上的結點。0 <= K <= 1000
.
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 }
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 }