在二叉树中找最近公共父节点。分为两种情况,一种是有父指针,一种没有父指针。
#include<iostream> struct Node { int data; Node* left; Node* right; Node* parent; Node() :left(NULL), right(NULL), parent(NULL) {} }; int getDpeth(Node *n)//结点n到根节点深度 { int count = 0; while (n) { ++count; n = n->parent; } return count; } Node* findNearestCommonAncestor(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* Ancestor = findNearestCommonAncestor(A[7], A[6]); }
#include<iostream> struct Node { int data; Node* left; Node* right; Node() :left(NULL), right(NULL) {} }; //计算当前结点包含n1、n2个数 int countMatch(Node *current, Node* n1, Node* n2) { if (current == NULL) return 0; int count = countMatch(current->left, n1, n2) + countMatch(current->right, n1, n2); if (current == n1 || current == n2) return 1 + count; return count; } Node* findLCA(Node* root, Node* n1, Node* n2) { if (root == NULL) return NULL; if (root == n1 || root == n2) return root; int count = countMatch(root->left, n1, n2);//左子树包含n1和n2的个数 if (count == 1) return root;//左子树一个,右子树肯定也有一个 else if (count == 2)//都在左子树 return findLCA(root->left, n1, n2); else//都在右子树 return findLCA(root->right, n1, n2); } 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]->right = A[i * 2 + 2]; } Node* Ancestor = findLCA(A[0],A[7], A[10]); }
#include<iostream> struct Node { int data; Node* left; Node* right; Node() :left(NULL), right(NULL) {} }; Node* findLCA(Node *root, Node* n1, Node* n2) { if (root == NULL)//没找到 return NULL; if (root == n1 || root == n2)//找到 return root; Node* L = findLCA(root->left, n1, n2);//左子树 Node* R = findLCA(root->right, n1, n2);//右子树 //当前结点左右子树都找到了n1和n2,那么这个结点就是LCA结点 if (L != NULL&R != NULL) return root; //否则是不为NULL的结点,或者两个都为NULL else return L !=NULL ? L : R; } 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]->right = A[i * 2 + 2]; } Node* Ancestor = findLCA(A[0], A[7], A[10]); }
原文地址:http://blog.csdn.net/kangroger/article/details/40392925