题目:给定一颗二叉树,有两个节点分别为n1和n2,写出程序找到最近的公共祖先,样例如下图:
方法一:(存储存储根到n1以及根到n2的路径)
第一步:找到根到n1并存储在向量或数组中
第二步:找到根到n2的路径并把它存储在另外的向量组中
第三步:遍历这两个路径直至数组中的值相同,返回公共元素。
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
struct Node
{
int key;
struct Node *left, *right;
};
Node * newNode(int k)
{
Node *temp = new Node;
temp->key = k;
temp->left = temp->right = NULL;
return temp;
}
bool findPath(Node *root, vector<int> &path, int k)
{
if (root == NULL) return false;
path.push_back(root->key);
if (root->key == k)
return true;
if ((root->left && findPath(root->left, path, k)) ||
(root->right && findPath(root->right, path, k)))
return true;
path.pop_back();
return false;
}
int findLCA(Node *root, int n1, int n2)
{
vector<int> path1, path2;
if (!findPath(root, path1, n1) || !findPath(root, path2, n2))
return-1;
int i;
for (i = 0; i < path1.size() && i < path2.size(); i++)
if (path1[i] != path2[i])
break;
return path1[i - 1];
}
int _tmain(int argc, _TCHAR* argv[])
{
Node * root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
cout << "LCA(4, 5) = " << findLCA(root, 4, 5);
cout << "\nLCA(4, 6) = " << findLCA(root, 4, 6);
cout << "\nLCA(3, 4) = " << findLCA(root, 3, 4);
cout << "\nLCA(2, 4) = " << findLCA(root, 2, 4);
return 0;
}