3 line C++ code


  • 0
    T

    /**

    • 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)<=0) return root;
      if(root->val > p->val) return lowestCommonAncestor(root->left,p,q);
      else return lowestCommonAncestor(root->right,p,q);
      }
      };

  • 0
    G

    Same code here, just format for readability

    struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
        if ((root->val - p->val) * (root->val - q->val) <=0)
        // p & q on different sides, or p or is root itself
            return root;
        else if (root->val > p->val)
            return lowestCommonAncestor(root->left, p, q);
        else
            return lowestCommonAncestor(root->right, p, q);
    }

Log in to reply
 

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