类似于哈夫曼树的编码形式,对树编码,左子树0,右子树1。对树进行深搜,找到最长匹配串就是最优公共父节点。
/*Design an algorithm and write code to find the first common ancestor of two nodes
in a binary tree Avoid storing additional nodes in a data structure NOTE: This is not
necessarily a binary search tree
*/
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string a,b;
class Node{
public:
int data;
Node *lchild,*rchild,*parent;
Node(int a=0, Node*p=0):data(a),parent(p),rchild(0),lchild(0){}
};
class Tree{
public:
Node* root;
Tree():root(0){}
Tree(int ar[],int l){
root = 0;
for(int i = 0; i<l; i++)
insert(ar[i]);
}
void insert(int);
bool is_empty(){ return !root;}
void dfs(Node*,int,int,string);
void destroy(Node*);
};
void Tree::insert(int k){
if(is_empty())
root = new Node(k);
else{
Node* temp = root;
Node* parent;
while(temp){
parent =temp;
if(temp->data > k)
temp = temp->lchild;
else temp = temp->rchild;
}
temp = new Node(k,parent);
if(parent->data>k)
parent->lchild = temp;
else parent->rchild = temp;
}
}
void Tree::dfs(Node* r,int aa, int bb, string current)
{
if(!r){
current.erase(current.end()-1,current.end());
return;
}
if(r->data == aa) a = current;
if(r->data == bb) b = current;
dfs(r->lchild,aa,bb,current+'0');
dfs(r->rchild,aa,bb,current+'1');
if(current!= "")
current.erase(current.end()-1,current.end());
}
void Tree::destroy(Node* r){
if(r){
destroy(r->lchild);
destroy(r->rchild);
delete r;
}
}
int main(){
int ar[]={16,423,5,67,8,9,45,78,777,33,12,11,76,4,43,7};
Tree ll(ar,16);
ll.dfs(ll.root,11,4,"");
Node* k = ll.root;
for(int i = 0; a[i] == b[i];i++)
if(a[i] == '0') k = k->lchild;
else k = k->rchild;
cout<<k->data<<endl;
ll.destroy(ll.root);
}