Share my simple c++ code


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

  • 1
    S

    nice code, but what about if node p or q doesn't belong to this tree?


  • 0
    D

    thanks , that is a good question. But there is no such case in this problem. Because it is said that the two given nodes are in the BST .


Log in to reply
 

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