/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (nullptr == root) {
return root;
}
if (root == p or root == q) {
return root;
}
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (nullptr == left) {
return right;
}
if (nullptr == right) {
return left;
}
return root;
}
};
leetcode236 Lowest Common Ancestor of a Binary Tree
最新推荐文章于 2022-03-12 17:26:01 发布