判断一颗数上的两个节点的公共节点

定义一个二叉树

#include <stack>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <iostream>
using namespace std;

class Node{
public:
    int value;
    Node* left;
    Node* right;
    Node(int value):value(value){
        left = nullptr;
        right = nullptr;
    }
};

生成一个平衡二叉树,满二叉树, 完全二叉树

//生成一个完全二叉树
Node* fullTreeInit(){
    Node *head = new Node(1);
    head->left = new Node(2);
    head->right = new Node(3);
    head->left->left = new Node(4);
    head->left->right = new Node(5);
    head->right->left = new Node(6);
    head->right->right = new Node(7);
    return head;
}
//生成一个满二叉树
Node* treeInit(){
    Node *head = new Node(1);
    head->left = new Node(2);
    head->right = new Node(3);
    head->left->left = new Node(4);
    head->left->right = new Node(5);
    head->right->left = new Node(6);
    head->right->right = new Node(7);
    return head;
}

算法

//检测两个节点的公共父节点
//(哈希方法)
void getParentNode(Node *head, unordered_map<Node*, Node*> &hashMap){
    if(head == nullptr){
        return;
    }
    if(head->left!= nullptr){
        hashMap.insert(pair<Node*, Node*>(head->left, head));
    }
    if(head->right!= nullptr){
        hashMap.insert(pair<Node*, Node*>(head->right, head));
    }
    getParentNode(head->left, hashMap);
    getParentNode(head->right, hashMap);
}

Node* CommonParentNode(Node *head, Node *o1, Node *o2){
    if(head == nullptr || o1 == nullptr || o2 == nullptr){
        return nullptr;
    }
    unordered_map<Node*, Node*> hashMap;
    hashMap.insert(pair<Node*, Node*>(head, head));
    getParentNode(head, hashMap);

    unordered_set<Node*> hashSet;
    Node *parent = nullptr;
    Node *cur1 = o1;
    Node *cur2 = o2;
    hashSet.insert(cur1);
    while(cur1 != head){
        parent = hashMap[cur1];
        cur1 = parent;
        hashSet.insert(parent);
    }
    if(hashSet.find(cur2) != hashSet.end()){
        return cur2;
    }
    while(cur2 != head){
        parent = hashMap[cur2];
        cur2 = parent;
        if(hashSet.find(parent) != hashSet.end()){
            return parent;
        }
    }
    return nullptr;
}

//检测两个节点的公共父节点
//(动态规划方法)
Node* getCommonParent(Node* head, Node* o1, Node* o2){
    if(head == nullptr || head == o1 || head == o2){
        return head;
    }
    Node *parent1 = getCommonParent(head->left, o1, o2);
    Node *parent2 = getCommonParent(head->right, o1, o2);
    if(parent1 != nullptr && parent2 != nullptr){
        return head;
    }
    return parent1 != nullptr? parent1 : parent2;
}


posted @   蘑菇王国大聪明  阅读(58)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示