判断一颗数上的两个节点的公共节点
定义一个二叉树
#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;
}
主要是给自己看的,所以肯定会出现很多错误哈哈哈哈哈