问题
We can easily use the code to find LCA in Binary Search Tree:-
public static Node FindLCA(Node root, Node a, Node b)
{
if (root == null)
return null;
if (root.IData == a.IData || root.IData == b.IData)
return root;
if (root.RightChild != null && (root.RightChild.IData == a || root.RightChild.IData == b))
return root;
if (root.LeftChild != null && (root.LeftChild.IData == a || root.LeftChild.IData == b))
return root;
if (root.IData > a.IData && root.IData > b.IData)
return FindLCA(root.LeftChild, a, b);
if (root.IData < a.IData && root.IData < b.IData)
return FindLCA(root.RightChild, a, b);
else
return root;
}
Was wondering how to handle in case one of the nodes doesn't exist? One easy possible option could be, find if the nodes exist in the BST - this can be done in O(LogN) time and then if necessary call FindLCA? Any other options without first finding if keys exist or not?
EDIT I realized that I was missing some more conditions earlier, added them and also based on vvijay's answer below.
20
8 22
4 12
10 14
Questions:
- But now it fails to find LCA for 8 , 22 and says 22 instead of 20.
- Will the LCA(8, 12) be 8 or 20 - I think it should be 8 based on wiki's def of LCA (viz. where we allow a node to be a descendant of itself).
Any thoughts suggestions.?
回答1:
I think you can separate out the bad cases.
if (root == null) return null;
if (root.Idata == a.Idata || root.Idata == b.Idata) return root;
or just change the return null to return root in your code. So null return value would mean you don't have atleast one of the query nodes in the tree.
来源:https://stackoverflow.com/questions/8427656/find-lowest-common-ancestor-bst-when-one-or-both-nodes-doesnt-exist