#include <stdio.h>
typedef struct _treeNode{
struct _treeNode *left, *right;
int data;
}treeNode;
treeNode *findPorQ(treeNode *root, treeNode *p, treeNode *q){
if(root==NUll || root==p || root==q)return root;
treeNode *left = findPorQ(root->left, p, q);
treeNode *right = findPorQ(root->right, p, q);
return left == NULL ? right : (right == NULL ? left : root);
}
如果是二叉搜索树,则优化如下
#include <stdio.h>
typedef struct _treeNode{
struct _treeNode *left, *right;
int data;
}treeNode;
treeNode *findPorQ(treeNode *root, treeNode *p, treeNode *q){
if(p->data < root->data && q->data<root->data)
return findPorQ(root->left, p, q);
if(p->data > root->data && q->data > root->data)
return findPorQ(root->right, p, q);
return root;
}