JZ68 题解 | #二叉搜索树的最近公共祖先#
二叉搜索树的最近公共祖先
https://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
// 回溯算法
// 返回x的搜索路径
void GetParentTrack(TreeNode* root, int x, vector<int>& track) {
if (root == nullptr) {
return;
}
// 递归退出条件
// 找到了x,则退出递归
if (root->val == x) {
track.push_back(x);
return;
} else if (x < root->val) {
track.push_back(root->val);
GetParentTrack(root->left, x, track);
} else {
track.push_back(root->val);
GetParentTrack(root->right, x, track);
}
return;
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param p int整型
* @param q int整型
* @return int整型
*/
int lowestCommonAncestor(TreeNode* root, int p, int q) {
// write code here
int ans;
// 先找到p的父节点路径
vector<int> pTrack;
GetParentTrack(root, p, pTrack);
// 7 1 0
// 找到q的父节点路径
vector<int> qTrack;
GetParentTrack(root, q, qTrack);
// 7 1 4 3
// 由于二叉搜素数有序,查找路径是固定不变的
// 遍历p和q的遍历路径,找到最近的相同元素
int minLen = std::min(lenP, lenQ);
for (int i = minLen - 1; i >= 0; i--) {
if (pTrack[i] == qTrack[i]) {
ans = pTrack[i];
break;
}
}
return ans;
}
};
嘉士伯公司氛围 425人发布
查看9道真题和解析