/**
* 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) {
int a1 = p->val,a2 = q->val;
if(a1 > a2) swap(a1,a2);
while(1){
if(root->val < a1) root = root->right;
else if(root->val > a2)root = root->left;
else return root;
}
}
};leetcode 235. Lowest Common Ancestor of a Binary Search Tree
最新推荐文章于 2025-12-05 19:39:52 发布
本文介绍了一种求解二叉搜索树中两个节点最近公共祖先的方法。通过一次遍历,利用二叉搜索树特性,当根节点值大于两节点最大值时向左子树移动,反之则向右子树移动,直至找到公共祖先。
1068

被折叠的 条评论
为什么被折叠?



