0%

lowest-common-ancestor-of-a-binary-search-tree

Lowest Common Ancestor of a Binary Search Tree – LeetCode 235

Problem

Description

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 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->val > p->val && root->val > q->val) return lowestCommonAncestor(root->left,p,q);
if(root->val < p->val && root->val < q->val) return lowestCommonAncestor(root->right,p,q);
return root;
}
};

思路

使用BFS判断,得益于BST的大小关系可以直接搜索,时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$22$ ms,排名$5.84\%$

Better

思路

还没看到更好的思路。