[刷题] 235 Lowest Common Ancestor of a Binary Search Tree

要求

  • 给定一棵二分搜索树和两个节点,寻找这两个节点的最近公共祖先

示例

  • 2和8的最近公共祖先是6
  • 2和4的最近公共祖先是2

思路

  • p q<node
  • node<p q
  • p<=node<=q

实现

 1 class Solution {
 2 public:
 3     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
 4         
 5         assert( p != NULL && q != NULL );
 6         
 7         if( root == NULL )
 8             return NULL;
 9         
10         if( p->val < root->val && q->val < root->val )
11             return lowestCommanAncestor( root->left , p , q );
12         if( p->val > root->val && q->val > root->val )
13             return lowestCommanAncestor( root->right , p , q );
14             
15         return root;
16     }    
17 };
View Code

相关

  • 98 Validate Binary Search Tree
  • 450 Delete Node in a BST
  • 108 Convert Sorted Array to Binary Search Tree
  • 230 Kth Smallest Element in a BST
  • 236 Lowest Common Ancestor of a Binary Tree

 

posted @ 2020-04-12 10:53  cxc1357  阅读(135)  评论(0编辑  收藏  举报