笔试-最近公共父节点

设计一个算法,找出二叉树上任意两个节点的最近共同父节点(假设每个子结点都有指向父节点的指针)要求时间复杂度低于O(n^2).

#include <iostream>
using namespace std;
class Node{
public:
    int data;
    Node* left;
    Node* right;
    Node* parent;
    Node() :left(NULL), right(NULL), parent(NULL){}
};
//结点n到根节点的深度
int GetDpeth(Node *n){
    int count = 0;
    while (n){
        ++count;
        n = n->parent;
    }
    return count;
}
Node* find(Node* n1, Node* n2){
    int depth1 = GetDpeth(n1);
    int depth2 = GetDpeth(n2);
    //移动同一深度
    while (depth1 > depth2){
        n1 = n1->parent;
        --depth1;
    }
    while (depth1 < depth2){
        n2 = n2->parent;
        --depth2;
    }
    while (n1 != n2){
        n1 = n1->parent;
        n2 = n2->parent;
    }
    return n1;
}
//测试
int main(){
    Node* A[11];
    for (int i = 0; i < 11; ++i){
        A[i] = new Node();
        A[i]->data = i;
    }
    for (int i = 0; i < 5; ++i){
        A[i]->left = A[i * 2 + 1];
        A[i * 2 + 1]->parent = A[i];
        A[i]->right = A[i * 2 + 2];
        A[i * 2 + 2]->parent = A[i];
    }
    Node *An = find(A[7], A[6]);
    cout << An->data<< endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值