您的位置:首页 > 编程语言 > C语言/C++

剑指offer(面试题50)树中两结点的最低公共祖先(C++实现)

2018-01-01 16:32 309 查看
#include <iostream>
#include <vector>

using namespace std;

struct TreeNode {
int val;
TreeNode * left;
TreeNode * right;
};

bool FindPath(TreeNode * root, TreeNode * pNode, vector<TreeNode *> & vec) {
if (root == nullptr || pNode == nullptr) {
return false;
}
vec.push_back(root);
if (root == pNode) {
return true;
}
if (FindPath(root->left, pNode, vec) || FindPath(root->right, pNode, vec)) { return true; }
vec.pop_back();
return false;
}

TreeNode * FindCommonParent(TreeNode * root, TreeNode * pNode1, TreeNode * pNode2) {
if (root == nullptr || pNode1 == nullptr || pNode2 == nullptr) {
return nullptr;
}
vector<TreeNode *> vec1;
bool hasPath1 = FindPath(root, pNode1, vec1);
vector<TreeNode *> vec2;
bool hasPath2 = FindPath(root, pNode2, vec2);
if (hasPath1 && hasPath2) {
int i = 0;
while (vec1[i] == vec2[i]) {
i++;
}
return vec1[i-1];
}
return nullptr;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: