|
| 1 | +/* |
| 2 | +Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. |
| 3 | +
|
| 4 | +According to the definition of LCA on Wikipedia: The lowest common ancestor is defined between two nodes p and qas the lowest node in T that has both p and qas descendants (where we allow a node to be a descendant of itself). |
| 5 | +
|
| 6 | +Given binary search tree: root =[6,2,8,0,4,7,9,null,null,3,5] |
| 7 | +
|
| 8 | +
|
| 9 | +
|
| 10 | +
|
| 11 | +Example 1: |
| 12 | +
|
| 13 | +Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 |
| 14 | +Output: 6 |
| 15 | +Explanation: The LCA of nodes 2 and 8 is 6. |
| 16 | +Example 2: |
| 17 | +
|
| 18 | +Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 |
| 19 | +Output: 2 |
| 20 | +Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. |
| 21 | +
|
| 22 | +
|
| 23 | +Note: |
| 24 | +
|
| 25 | +All of the nodes' values will be unique. |
| 26 | +p and q are different and both values willexist in the BST. |
| 27 | +
|
| 28 | +来源:力扣(LeetCode) |
| 29 | +链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree |
| 30 | +著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 |
| 31 | +*/ |
| 32 | + |
| 33 | +#define NULL 0 |
| 34 | + |
| 35 | +struct TreeNode { |
| 36 | + int val; |
| 37 | + TreeNode *left; |
| 38 | + TreeNode *right; |
| 39 | + TreeNode(int x) : val(x), left(NULL), right(NULL) {} |
| 40 | +}; |
| 41 | + |
| 42 | +class Solution { |
| 43 | + private: |
| 44 | + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q, |
| 45 | + bool& is_p, bool& is_q){ |
| 46 | + is_p = (root==p)?true:false; is_q = (root==q)?true:false; |
| 47 | + if(root==NULL) return NULL; |
| 48 | + TreeNode* res; |
| 49 | + // left |
| 50 | + bool is_p_l, is_q_l; |
| 51 | + res = lowestCommonAncestor(root->left, p, q, is_p_l, is_q_l); |
| 52 | + is_p |= is_p_l; is_q |= is_q_l; |
| 53 | + if(res) return res; |
| 54 | + else if(is_p&&is_q) return root; |
| 55 | + // right |
| 56 | + bool is_p_r, is_q_r; |
| 57 | + res = lowestCommonAncestor(root->right, p, q, is_p_r, is_q_r); |
| 58 | + is_p |= is_p_r; is_q |= is_q_r; |
| 59 | + if(res) return res; |
| 60 | + else if(is_p&&is_q) return root; |
| 61 | + // return |
| 62 | + return NULL; |
| 63 | + } |
| 64 | + public: |
| 65 | + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { |
| 66 | + bool is_p, is_q; |
| 67 | + return lowestCommonAncestor(root, p, q, is_p, is_q); |
| 68 | + } |
| 69 | +}; |
0 commit comments