【学习点滴-数据结构-二叉树】求二叉树中某两个节点的最近公共祖先

解法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 


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值