MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / dfs

Function dfs

kotlin/Trees/LowestCommonAncestor.kt:19–40  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

17}
18
19fun dfs(node: TreeNode?, p: TreeNode?, q: TreeNode?, lca: MutableList<TreeNode?>): Boolean {
20 // Base case: a null node is neither 'p' nor 'q'.
21 if (node == null) {
22 return false
23 }
24 val nodeIsPOrQ = node == p || node == q
25 // Recursively determine if the left and right subtrees contain 'p'
26 // or 'q'.
27 val leftContainsPOrQ = dfs(node.left, p, q, lca)
28 val rightContainsPOrQ = dfs(node.right, p, q, lca)
29 // If two of the above three variables are true, the current node is
30 // the LCA.
31 if ((nodeIsPOrQ && leftContainsPOrQ) ||
32 (nodeIsPOrQ && rightContainsPOrQ) ||
33 (leftContainsPOrQ && rightContainsPOrQ)
34 ) {
35 lca[0] = node
36 }
37
38 // Return true if the current subtree contains 'p' or 'q'.
39 return nodeIsPOrQ || leftContainsPOrQ || rightContainsPOrQ
40}

Callers 1

lowestCommonAncestorFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected