我试图从破解代码面试的书中解决问题 4.7(非常酷的书!)。
设计一个算法并编写代码来找到二叉树中两个节点的第一个共同祖先。避免在数据结构中存储额外的节点。注意:这不一定是二叉搜索树。
我想出了这个解决方案,它甚至与书中提供的解决方案都不相近。我想知道是否有人可以找到它的任何缺陷?
解决方案:我创建了一个包装类来保存第一个共同祖先(如果找到的话)和 2 个布尔值来跟踪递归搜索树时是否找到了 a 或 b。请阅读下面代码中添加的注释。
public static void main (String args[]){
NodeTree a, b, head, result; //initialise and fill with data
fillTreeTestData(head);
pickRandomNode(a);
pickRandomNode(b);
result = commonAnsestor(a,b,head);
if(result != null)
System.out.println("First common ansestor "+result);
else
System.out.println("Not found");
}
class TreeNode{
Object value;
TreeNode right, left;
}
class WraperNodeTree{
boolean found_a;
boolean found_b;
NodeTree n;
WraperNodeTree (boolean a, boolean b, NodeTree n){
this.n = n;
this.a = a;
this.b = b;
}
}
static WraperNodeTree commonAnsestor(NodeTree a, NodeTree b, NodeTree current){
// Let's prepare a wraper object
WraperNodeTree wraper = new WraperNodeTree(false, false, null);
// we reached the end
if(current == null) return wraper;
// let's check if current node is either a or b
if(a != null)
wraper.found_a = current.value.equals(a.value);
else if(b != null)
wraper.found_b = current.value.equals(b.value);
else
return wraper; // if both are null we don't need to keep searching recoursively
// if either a or b was found let's stop searching for it for performance
NodeTree to_search_a = wraper.found_a ? null : a;
NodeTree to_search_b = wraper.found_b ? null : b;
// let's search the left
WraperNodeTree wraperLeft = common(to_search_a,to_search_b,current.left);
// if we already have a common ancester just pass it back recoursively
if(wraperLeft.n != null) return wraperLeft;
WraperNodeTree wraperRight = common(to_search_a,to_search_b,current.right);
if(wraperRight.n != null)return wraperRight;
// keep the wraper up to date with what we found so far
wraper.a = wraper.found_a || wraperLeft.found_a || wraperRight.found_a;
wraper.b = wraper.found_b || wraperLeft.found_b || wraperRight.found_b;
// if both a and b were found, let's pass the current node as solution
if(wraper.found_a && wraper.found_b)
wraper.n = current;
return wraper;
}