【二叉树 - LeetCode】236. 二叉树的最近公共祖先
题目:
236. 二叉树的最近公共祖先 - 力扣(LeetCode)
题解:
深入理解递归后,这个题目就很好理解。
在每个子树中查找 p 和 q。如果同一侧子树中同时找到 p 和 q ,那么往上走的过程中,遇到的就是 LCA。如果一侧有一个,那么root就是LCA。
/*** 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(!root || root == p || root == q){return root;}TreeNode* l = lowestCommonAncestor(root->left,p,q);TreeNode* r = lowestCommonAncestor(root->right,p,q);if(l && r) return root;return l ? l : r;}
};
优秀题解:
236. 二叉树的最近公共祖先 - 力扣(LeetCode)