hxc丶 2021-11-29 18:26 采纳率: 78.3%
浏览 36
已结题

寻找完全二叉树的最近公共祖先问题

编译通过了但是代码没有输出

代码如下
#include
#include
using namespace std;

struct TreeNode{
    int x;
    TreeNode* left;
    TreeNode* right;
};

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q){
    if(root==p||root==q||!root)return root;
       
    TreeNode* left=lowestCommonAncestor(root->left,p,q);
    TreeNode* right=lowestCommonAncestor(root->right,p,q);
       
    if(!left&&!right)return NULL;
    else if(left&&!right)return left;
    else if(right&&!left)return right;
       
    return root;
}

TreeNode* Search(TreeNode* &root,int i){
    if((root->x)==i){
        return root;
    }
    TreeNode* pNode=NULL;
    if(root->left!=NULL){
        pNode=Search(root->left,i);
        if(!pNode){
            return pNode;
        }
    }
    if(root->right!=NULL){
        pNode=Search(root->right,i);
        if(!pNode){
            return pNode;
        }
    }
    return NULL;
}

void CreateTree(TreeNode* &root,int a,int len,int loc)
{
    if(loc>=len){root=NULL;return;}
    root->x=a[loc];
    CreateTree(root->left,a,len,2
loc+1);
    CreateTree(root->right,a,len,2*(loc+1));
}

int main(){
    TreeNode* root=(TreeNode*)malloc(sizeof(TreeNode));
    int a[1000];
    for(int i=0;i<1000;i++){
        a[i]=i+1;
    }
    CreateTree(root,a,999,0);
    int m,n,Y;
    cin>>Y;
    for(int i=0;i<Y;i++){
        cin>>m>>n;
        TreeNode* p=Search(root,m);
        TreeNode* q=Search(root,n);
        TreeNode* r=lowestCommonAncestor(root,p,q);
        cout<x<<endl;
    }
}

求大神解答!

  • 写回答

1条回答 默认 最新

  • 有问必答小助手 2021-12-01 09:40
    关注

    你好,我是有问必答小助手,非常抱歉,本次您提出的有问必答问题,技术专家团超时未为您做出解答


    本次提问扣除的有问必答次数,已经为您补发到账户,我们后续会持续优化,扩大我们的服务范围,为您带来更好地服务。

    评论

报告相同问题?

问题事件

  • 系统已结题 12月7日
  • 创建了问题 11月29日

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘