c# – 在二叉搜索树中查找最低共同祖先
发布时间:2020-12-15 21:27:22 所属栏目:百科 来源:网络整理
导读:我有以下代码来查找最低共同祖先(同时具有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 (
我有以下代码来查找最低共同祖先(同时具有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 题 以下情况失败:
有什么想法吗? 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); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |