#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(): val(0), left(nullptr), right(nullptr) {}
TreeNode(int x): val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right): val(x), left(left), right(right) {}
};
class Solution {
public:
/*
利用后序遍历进行遍历整棵树:如果找到一个节点,发现左子树出现节点p、右子树出现节点q,或左子树出现节点q、右子树出现节点p,那么该节点就是节点p和q的最近公共祖先。
*/
// 1.确定递归函数入参及返回值
// 返回值表示是否找到了节点p或节点q,同时返回最近公共祖先节点。因此,函数返回值类型为TreeNode*,如果遇到p或者q,就把q或者p返回,返回值不为空,就说明找到了q或者p。
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
// 2.确定递归函数的终止条件
if(root == p || root == q || root == nullptr) return root;
// 3.确定单层递归逻辑
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(left != nullptr && right != nullptr) return root;
if(left == nullptr && right != nullptr) return right;
if(left != nullptr && right == nullptr) return left;
else return nullptr;
}
};
【LeetCode-236 | 二叉树的最近公共祖先】
原创CurryCoder 博主文章分类:LeetCode刷题记录 ©著作权
©著作权归作者所有:来自51CTO博客作者CurryCoder的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
【数据结构】二叉树的存储结构
【数据结构】第五章——树与二叉树详细介绍二叉树的存储结构……
二叉树 数据结构 C语言 -
LeetCode 236:二叉树的最近公共祖先
LeetCode 236:二叉树的最近公共祖先
递归 子树 前序遍历 中序遍历 编程技巧 -
LeetCode. 236二叉树的最近公共祖先
文章目录题目描述思路扩展题目描述给定一颗二叉树,以及2个指定节点p , q,找到这2个节点的最近公共祖先。注意,
leetcode 算法 dfs 子树 最近公共祖先 -
【LeetCode 43】236.二叉树的最近公共祖先
【LeetCode 43】236.二叉树的最近公共祖先
leetcode 算法 深度优先 递归函数 子树 -
Java实现 LeetCode 236 二叉树的最近公共祖先
...
最近公共祖先 二叉树 结点 百度 JAVA -
process model15的结果解释
回顾往昔: &nb
软件测试 测试过程 软件开发