设计一个算法,找出二叉树上任意两个节点的最近共同父节点(假设每个子结点都有指向父节点的指针)要求时间复杂度低于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;
}