最低公共祖先

#include<iostream>
#include<vector>
#include<algorithm>
#include<stdint.h>
using namespace std;
#include<list>
#include<map>
#include<queue>


struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool getpath(TreeNode* root, vector<TreeNode*> &path,TreeNode* p)
{
if (root == NULL) return false;
bool flag1 = false, flag2 = false;

path.push_back(root);
if (root == p) return true;

flag1=getpath(root->left,path,p);
flag2=getpath(root->right, path, p);

if (!(flag1||flag2))
path.pop_back();

if (flag1 || flag2)
return true;
else
return false;
}


TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {

vector<TreeNode*> path1;
vector<TreeNode*> path2;
getpath(root, path1, p);
getpath(root, path2, q);

int i = 0;
while (i<path1.size()&&i<path2.size())
{
if (path1[i] != path2[i])
{
return path1[i - 1];
}
i++;
}

if (path1[i - 1] == path2[i - 1])
return path1[i - 1];
else return NULL;
}


int main()
{
TreeNode n1(1), n2(2), n3(3), n4(4), n5(5), n6(6), n7(7),n8(8);
n1.left = &n2;
n1.right = &n3;
n2.left = &n4;
n2.right = &n5;
n3.left = &n6;
n4.left = &n7;
n6.left = &n8;
TreeNode* tmp=lowestCommonAncestor(&n1,&n7,&n2);
cout << tmp->val << endl;
return 0;
}

原文地址:https://www.cnblogs.com/wuxiangli/p/5643149.html