微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 在二叉搜索树中查找最低共同祖先

我有以下代码来查找最低共同祖先(同时具有a和b作为后代的最低节点):

public static Node LCA(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.IData || root.RightChild.IData == b.IData))
        return root;

    if (root.LeftChild != null && (root.LeftChild.IData == a.IData || root.LeftChild.IData == b.IData))
        return root;

    if (root.IData > a.IData && root.IData > b.IData)
        return LCA(root.LeftChild,a,b);
    else if (root.IData < a.IData && root.IData < b.IData)
        return LCA(root.RightChild,b);
    else
        return root;
}

二叉搜索树是

20
                     /  \
                    8    22
                  /   \
                 4     12 
                      /  \
                    10    14

以下情况失败:

LCA (4,8) = 20 but should be 8.

LCA (8,12) = 20 but should be 8

LCA (8,23) = 20,non-existent number (23) as parameter.

有什么想法吗?

Node在哪里

class Node
{
 public int IData {get; set;}
 public Node RightChild {get; set;}
 public Node LeftChild {get; set;}
}

解决方法

如果root的IData与a和b都不同,但是root的子节点之一具有与两者中的任何一个相同的IData,则返回root,但是根据您的定义,如果两个节点都在同一个节点中,则应返回子节点子树.由于您还要检查两个节点是否实际位于树中,因此必须在返回之前执行该检查.

public static Node LCA(Node root,Node b)
{
    if (root == null) return null;
    // what if a == null or b == null ?
    Node small,large,current = root;
    if (a.IData < b.IData)
    {
        small = a;
        large = b;
    }
    else
    {
        small = b;
        large = a;
    }
    if (large.IData < current.IData)
    {
        do
        {
            current = current.LeftChild;
        }while(current != null && large.IData < current.IData);
        if (current == null) return null;
        if (current.IData < small.IData) return LCA(current,small,large);
        // if we get here,current has the same IData as one of the two,the two are
        // in different subtrees,or not both are in the tree
        if (contains(current,small) && contains(current,large)) return current;
        // at least one isn't in the tree,return null
        return null;
    }
    else if (current.IData < small.IData)
    {
        // the symmetric case,too lazy to type it out
    }
    else // Not both in the same subtree
    {
        if (contains(current,large)) return current;
    }
    return null; // at least one not in tree
}

public static bool contains(Node root,Node target)
{
    if (root == null) return false;
    if (root.IData == target.IData) return true;
    if (root.IData < target.IData) return contains(root.RightChild,target);
    return contains(root.LeftChild,target);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐