Skip to content

Instantly share code, notes, and snippets.

@charlieInDen
Created January 20, 2021 06:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charlieInDen/2145a45f2beef119824e8b91fbb7a05b to your computer and use it in GitHub Desktop.
Save charlieInDen/2145a45f2beef119824e8b91fbb7a05b to your computer and use it in GitHub Desktop.
func distanceK(_ root: TreeNode?, _ target: TreeNode?, _ K: Int) -> [Int] {
guard let root = root else { return [] }
var parentDict = [TreeNode: TreeNode]()
dfsFillParentDict(root, parentDict)
var queue = [root, nil]
var level = 0
var visited = Set<TreeNode>()
while level != K && !queue.isEmpty {
if let node = queue.removeFirst() {
if let left = node.left {
queue.append(left)
}
if let right = node.right {
queue.append(right)
}
if let parent = parentDict[node] {
queue.append(parent)
}
visited.insert(node)
} else {
if !queue.isEmpty{
queue.append(nil)
level += 1
}
}
}
return queue
}
func dfsFillParentDict(_ root: TreeNode?, _ parentDict: inout [TreeNode: TreeNode]) {
guard let root = root else { return }
dfsFillParentDict(root.left)
dfsFillParentDict(root.right)
if let left = root.left {
parentDict[left] = root
}
if let right = root.right {
parentDict[right] = root
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment