思路:
出自此处,请点击!
这里的话,用dfs去搜索,其实是把整棵树搜索的(除了p,q节点以下的子树没有搜索外,哪怕你在某root的左子树找到了p,q的最近公共祖先,它还是会把root的右边进行搜索的)
代码:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if(left == null && right == null) return null; // 1.
if(left == null) return right; // 3.
if(right == null) return left; // 4.
return root; // 2. if(left != null and right != null)
}
}
二叉搜索树的最近公共祖先
思路:
这道题比起上道题来说是比较简单的,因为这是二叉搜索树,是有规律的,(这里我们假设p->val是比q->val小的)当某个节点是这两个节点的最近公共祖先,那么它的前提就是某子树root的val是比p->val大,比q->val小的。否则就看看走哪个分支子树。具体看代码。
代码:
/**
* 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(p->val > q->val) swap(p,q);
while(root!=NULL){
if(root->val < p->val) root = root->right;
else if(root->val > q->val) root = root->left;
else break;
}
return root;
}
};