?LeetCode刷題實(shí)戰(zhàn)236:二叉樹的最近公共祖先
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
示例

解題
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
stack<TreeNode *> stack;
stack.push(root);
map<TreeNode *, TreeNode *> parent_map;
parent_map[root] = NULL;
while(parent_map.find(p) == parent_map.end() || parent_map.find(q) == parent_map.end()){
TreeNode *node = stack.top();
stack.pop();
if(node -> left != NULL){
parent_map[node -> left] = node;
stack.push(node -> left);
}
if(node -> right != NULL){
parent_map[node -> right] = node;
stack.push(node -> right);
}
}
set<TreeNode *> p_parent;
p_parent.insert(p);
// 迭代父節(jié)點(diǎn)map,這里的循環(huán)邏輯為,父節(jié)點(diǎn)字典中如果一直能夠找到p節(jié)點(diǎn)的父節(jié)點(diǎn),就進(jìn)入循環(huán)
// 這樣可以一直得到p節(jié)點(diǎn)的父節(jié)點(diǎn)列表。
while(parent_map.find(p) != parent_map.end()){
p_parent.insert(parent_map[p]);
p = parent_map[p];
}
// 同理遍歷q節(jié)點(diǎn)的父節(jié)點(diǎn)列表,因?yàn)槭悄嫘虮闅v,所以當(dāng)它存在于p節(jié)點(diǎn)的列表時,找到的就是p和q的最近公共祖先
while(parent_map.find(q) != parent_map.end()){
if(p_parent.find(q) != p_parent.end()){
return q;
}
q = parent_map[q];
}
return root;
}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
int num = contain_node(root, p, q);
return ans;
}
int contain_node(TreeNode* root, TreeNode* p, TreeNode* q){
if(!root) return 0;
int mid = 0;
if(root == p || root == q) mid = 1;
int left = contain_node(root -> left, p, q);
if(mid + left == 2){
if(!ans) ans = root;
return 2;
}
int right = contain_node(root -> right, p, q);
if(left + right + mid >= 2){
if(!ans) ans = root;
return 2;
}
return left + mid + right;
}
private:
TreeNode* ans = NULL;
};
LeetCode1-220題匯總,希望對你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)221:最大正方形
LeetCode刷題實(shí)戰(zhàn)222:完全二叉樹的節(jié)點(diǎn)個數(shù)
LeetCode刷題實(shí)戰(zhàn)223:矩形面積
LeetCode刷題實(shí)戰(zhàn)224:基本計算器
LeetCode刷題實(shí)戰(zhàn)225:用隊(duì)列實(shí)現(xiàn)棧
LeetCode刷題實(shí)戰(zhàn)226:翻轉(zhuǎn)二叉樹
LeetCode刷題實(shí)戰(zhàn)227:基本計算器 II
LeetCode刷題實(shí)戰(zhàn)228:匯總區(qū)間
LeetCode刷題實(shí)戰(zhàn)229:求眾數(shù) II
LeetCode刷題實(shí)戰(zhàn)230:二叉搜索樹中第K小的元素
LeetCode刷題實(shí)戰(zhàn)231:2的冪
LeetCode刷題實(shí)戰(zhàn)232:用棧實(shí)現(xiàn)隊(duì)列
LeetCode刷題實(shí)戰(zhàn)233:數(shù)字 1 的個數(shù)
LeetCode刷題實(shí)戰(zhàn)234:回文鏈表
LeetCode刷題實(shí)戰(zhàn)235:二叉搜索樹的最近公共祖先
評論
圖片
表情
