Created
July 27, 2021 14:17
-
-
Save SandeepAggarwal/e6d065d564c4b6e2b4e68f044af55eb9 to your computer and use it in GitHub Desktop.
Prints a path from root node to a specified node in a tree
This file contains hidden or 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
import Foundation | |
class TreeNode { | |
var data: Int | |
var left: TreeNode? | |
var right: TreeNode? | |
init(data: Int) { | |
self.data = data | |
} | |
} | |
class BinaryTree { | |
var root: TreeNode | |
init(root: TreeNode) { | |
self.root = root | |
} | |
func printPathFromRoot(to node: TreeNode) -> [Int] { | |
pathFromRoot(to: node).compactMap { $0.data } | |
} | |
func pathFromRoot(to node: TreeNode) -> [TreeNode] { | |
if root.left == nil, root.right == nil { | |
return [root] | |
} | |
return path(from: root, to: node) | |
} | |
func path(from node1: TreeNode, to node2: TreeNode) -> [TreeNode] { | |
if node1.left?.data == node2.data || node1.right?.data == node2.data { | |
return [node1, node2] | |
} | |
if let left = node1.left { | |
let leftPath = path(from: left, to: node2) | |
if !leftPath.isEmpty { | |
return [node1] + leftPath | |
} | |
} | |
if let right = node1.right { | |
let rightPath = path(from: right, to: node2) | |
if !rightPath.isEmpty { | |
return [node1] + rightPath | |
} | |
} | |
return [] | |
} | |
} | |
let node20 = TreeNode(data: 20) | |
let node8 = TreeNode(data: 8) | |
let node22 = TreeNode(data: 22) | |
let node5 = TreeNode(data: 5) | |
let node3 = TreeNode(data: 3) | |
let node25 = TreeNode(data: 25) | |
let node10 = TreeNode(data: 10) | |
let node14 = TreeNode(data: 14) | |
node20.left = node8 | |
node20.right = node22 | |
node22.right = node25 | |
node8.left = node5 | |
node8.right = node3 | |
node3.left = node10 | |
node3.right = node14 | |
let tree = BinaryTree(root: node20) | |
print("path to node: \(tree.printPathFromRoot(to: node14))") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment