题目来源
和上一道题类似,不过树改成了普通的二叉树。
然后我又不会了,实际上还是很简单…想了想也不是很简单,想法还挺奇妙的。
就是假如左子树有有一个,右子树也有一个,那么就是root。假如左子树没有,那么就往右子树找。
代码如下:
/**
* 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 || p == root || q == root)
return root;
TreeNode *left = lowestCommonAncestor(root->left, p, q);
TreeNode *right = lowestCommonAncestor(root->right, p, q);
return !left ? right : (!right ? left : root);
}
};