Error: cannot solve it, use the tree solving pattern: end_condition/base cases;do_something_for_root;left = func(root-left);right = func(root-right);return something; In here, for lca(root, p, q), we first have ending/base case: if(root ==
Error:
cannot solve it, use the tree solving pattern:
end_condition/base cases;
do_something_for_root;
left = func(root->left);
right = func(root->right);
return something;
In here, for lca(root, p, q), we first have ending/base case:
if(root == q)
return q;
if(root == p)
return q;
if(root == null)
return null;
For first two cases, it means that in lca(root, p, q), we found one of node, and for the other root, either it is not within the root(i.e. equal to null) or in the left/right subtree. In both case we can know the lca is the one we found so far.
The last case means we cannot found any of them, return null.
For recursion:
left = lca(root.left, p, q);
right = lca(root.right, p, q);
if(left != null && right != null)
return root;
else if(left != null)
return left;
else if(right != null)
return right;
else
return null;
It is easy to understand, I will not explain it.