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

Function dfs

cpp/Trees/lowest_common_ancestor.cpp:21–36  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

19}
20
21bool dfs(TreeNode* node, TreeNode* p, TreeNode* q, TreeNode*& lca) {
22 // Base case: a null node is neither 'p' nor 'q'.
23 if (!node)
24 return false;
25 bool nodeIsPOrQ = (node == p || node == q);
26 // Recursively determine if the left and right subtrees contain 'p'
27 // or 'q'.
28 bool leftContainsPOrQ = dfs(node->left, p, q, lca);
29 bool rightContainsPOrQ = dfs(node->right, p, q, lca);
30 // If two of the above three variables are true, the current node is
31 // the LCA.
32 if (nodeIsPOrQ + leftContainsPOrQ + rightContainsPOrQ == 2)
33 lca = node;
34 // Return true if the current subtree contains 'p' or 'q'.
35 return nodeIsPOrQ || leftContainsPOrQ || rightContainsPOrQ;
36}

Callers 1

lowestCommonAncestorFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected