[Leetcode] #235 Lowest Common Ancestor of a Binary Search Tree

xiaoxiao2021-02-28  83

Discription

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

Solution

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (p->val > q->val) return lowestCommonAncestor(root, q, p); if (root->val >= p->val && root->val <= q->val) return root; else if(root->val>=p->val && root->val >= q->val){ return lowestCommonAncestor(root->left, p, q); } else return lowestCommonAncestor(root->right, p, q); }

GitHub-Leetcode:https://github.com/wenwu313/LeetCode

转载请注明原文地址: https://www.6miu.com/read-70094.html

最新回复(0)