【LeetCode 235】Lowest Common Ancestor of a Binary Search Tree

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

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______6______

       /              \

    ___2__          ___8__

   /      \        /      \

   0      _4       7       9

         /   \

         3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

思路:

  利用BST的性质,若待查找两个结点的数值都小于当前结点则向左边查找(若有一个等于当前结点则当前结点就是其最小的公共结点,结束查找),反之向右边查找(同理),若一个大于一个小于,则当前结点就是其最小的公共结点,结束查找。

C++:

 1 /**

 2  * Definition for a binary tree node.

 3  * struct TreeNode {

 4  *     int val;

 5  *     TreeNode *left;

 6  *     TreeNode *right;

 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}

 8  * };

 9  */

10 class Solution {

11 private:

12     TreeNode *l, *r, *ret;

13 public:

14 

15     void rec(TreeNode *root)

16     {

17         int v = root->val;

18         if(l->val <= v && r->val <= v)

19         {

20             if(v == l->val || v == r->val)

21             {

22                 ret = root;

23                 return ;

24             }

25             

26             if(root->left != 0)

27                 rec(root->left);

28         }

29         else if(l->val < v && v < r->val)

30         {

31             ret = root;

32             return ;

33         }

34         else if(l->val >= v && r->val >= v)

35         {

36             if(v == l->val || v == r->val)

37             {

38                 ret = root;

39                 return ;

40             }

41             

42             if(root->right != 0)

43                 rec(root->right);

44         }

45     }

46 

47     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {

48         if(root == 0)

49             return 0;

50         

51         if(p->val < q->val){

52             l = p;

53             r = q;

54         }

55         else{

56             l = q;

57             r = p;

58         }

59 

60         ret = 0;

61         

62         rec(root);

63         

64         return ret;

65     }

66 };

 

你可能感兴趣的:(Binary search)