C++, first you should know what the BST is。


  • 0
    B

    /**

    • 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 == NULL)
      return NULL;
      int max = p->val >q->val?p->val:q->val;
      int min = p->val >q->val?q->val:p->val;
      if(max<root->val)
      return lowestCommonAncestor(root->left,p,q);
      else if(min>root->val)
      return lowestCommonAncestor(root->right,p,q);
      else
      return root;
      }
      };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.