Find Lowest Common Ancestor BST when one or both node(s) doesnt exist

[亡魂溺海] 提交于 2019-12-08 06:32:02

问题


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:

  1. But now it fails to find LCA for 8 , 22 and says 22 instead of 20.
  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!