解法1
//思路,递归地在左右子树中找最低公共节点
//from v_july_v:http://blog.csdn.net/v_JULY_v?viewmode=contents
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define LEAF -1
struct BTreeNode{
int value;
BTreeNode * lchild;
BTreeNode * rchild;
};
BTreeNode * getCommonPa(BTreeNode * root,BTreeNode * x,BTreeNode *y){
if(root == NULL){
return NULL;
}
if(x == root || y == root){
return root;
}
BTreeNode * left = NULL,*right = NULL;
left = getCommonPa(root->lchild,x,y);
right = getCommonPa(root->rchild,x,y);
if(left == NULL){
return right;
}
if(right == NULL){
return left;
}
return root;
}
void visit(BTreeNode * x){
printf("%d\n",x->value);
}
void preOrder(BTreeNode * root){
if(root != NULL){
visit(root);
}
if(root->lchild != NULL){
preOrder(root->lchild);
}
if(root->rchild != NULL){
preOrder(root->rchild);
}
}
BTreeNode * createTree(){
BTreeNode * root;
int t;
scanf("%d",&t);
if(t == LEAF){
root = NULL;
}
else{
root = (BTreeNode *) malloc(sizeof(BTreeNode));
root->value = t;
root->lchild = createTree();
root->rchild = createTree();
}
return root;
}
main(){
BTreeNode * root = createTree();
BTreeNode * x,*y,*result,*re;
preOrder(root);
result = getCommonPa(root,root->rchild,root->lchild);
re = getCommonPa(root,root->lchild->rchild,root->lchild->lchild);
if(re != NULL){
printf("root->lchid == root->rchild %d\n",re->value);
}else{
printf("naive\n");
}
if(result != NULL){
printf("root->lchid == root->rchild %d\n",result->value);
}else{
printf("naive\n");
}
system("pause");
return 0;
}
解法2:额外两个栈,将从节点到跟的路径扔进栈中,然后弹出栈顶元素,直到最后两个栈的栈顶不相等时,之前弹出的就是最近公共节点。
//TODO