Created
January 20, 2021 06:12
-
-
Save charlieInDen/2145a45f2beef119824e8b91fbb7a05b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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