栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

定义一个二叉树
#include 
#include 
#include 
#include 
#include 
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 &hashMap){
    if(head == nullptr){
        return;
    }
    if(head->left!= nullptr){
        hashMap.insert(pair(head->left, head));
    }
    if(head->right!= nullptr){
        hashMap.insert(pair(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 hashMap;
    hashMap.insert(pair(head, head));
    getParentNode(head, hashMap);

    unordered_set 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;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1006895.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号