给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
#include <vector>
using namespace std;
class Solution {
public:
TreeNode * lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
TreeNode * result = nullptr;
vector<TreeNode*> path, p_result, q_result;
int finish_test = 0;
preorder(root, p, path, p_result, finish_test);
path.clear();
finish_test = 0;
preorder(root, q, path, q_result, finish_test);
unsigned path_len;
if(p_result.size() < q_result.size())
path_len = p_result.size();
else
path_len = q_result.size();
for (unsigned i = 0; i < path_len; i++)
if (p_result.at(i) == q_result.at(i))
result = p_result.at(i);
return result;
}
private:
static void preorder(
TreeNode* node,
TreeNode* search,
vector<TreeNode*> &path,
vector<TreeNode*> &result,
int& finish
)
{
if(!node || finish) {
return;
}
path.push_back(node);
if (node == search){
finish = 1;
result = path;
}
preorder(node->left, search, path, result, finish);
preorder(node->right, search, path, result, finish);
path.pop_back();
}
};