235. 二叉搜索树的最近公共祖先
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
思路
要记得利用到二叉搜索树的性质,当遍历到当前节点的值都比p、q小时,需要右移,当前节点的值比p、q大时,需要左移,遇到p、q需要分支时,就找到了最深的公共祖先。
代码
/**
* 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) {
TreeNode* ancestor = root;
while(true) {
if(ancestor -> val > p -> val && ancestor -> val > q -> val) {
ancestor = ancestor -> left;
}
else if(ancestor -> val < p -> val && ancestor -> val < q -> val) {
ancestor = ancestor -> right;
}
else {
break;
}
}
return ancestor;
}
};
236. 二叉树的最近公共祖先
唯一的不同就是这不是二叉搜索树,需要遍历整树,计算p或q是否在当前节点的左右节点,并且再额外判定当前节点的值是否和p、q相同即可,相同即证明最近公共祖先就是当前节点。
代码
/**
* 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* ancestor;
bool dfs(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr) {
return false;
}
bool lson = dfs(root -> left, p, q);
bool rson = dfs(root -> right, p, q);
if((lson && rson) || ((root -> val == p -> val || root -> val == q -> val) && (lson || rson))) {
ancestor = root;
return true;
}
return lson || rson || root -> val == p -> val || root -> val == q -> val;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
dfs(root, p, q);
return ancestor;
}
};