// Definition for a binary tree node.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
struct TreeNode{
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q){
if(root==NULL)
{
return NULL;
}
if(root->val==p->val||root->val==q->val)
{
return root;
}
struct TreeNode* lroot=lowestCommonAncestor(root->left,p,q);
struct TreeNode* rroot=lowestCommonAncestor(root->right,p,q);
if(lroot!=NULL&&rroot!=NULL)return root;
if(lroot==NULL&&rroot!=NULL)return rroot;
if(rroot==NULL&&lroot!=NULL)return lroot;
return NULL;
}
int main()
{
return 0;
}
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的
最新推荐文章于 2022-12-04 09:36:41 发布