Leetcode Lowest Common Ancestor of a Binary Search Tree (LCA recent public ancestor)

Source: Internet
Author: User

Test instructions: For a binary sorting tree, find the LCA of P and Q.

Idea: Given is a sort of tree, then each node must be greater than the largest in the left subtree, less than the smallest of the right sub-tree species. Based on this feature, it is much easier to find a LCA.

Three types of cases:

(1) P and Q are both on the left side of root, then the root Zuozi recursion.

(2) on the right side.

(3) One left and one right, then the root->val is certainly greater than 1 of them, less than the other.

1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8  * };9  */Ten classSolution { One  Public: ATreenode* lowestcommonancestor (treenode* root, treenode* p, treenode* q) {//This is a sort of tree ah!  -         if((root->val-p->val) * (root->val-q->val) <=0)//a big one will produce negative, or root for 1 of them, then 0 -             returnRoot; the         if(Max (P->val, Q->val) < Root->val)//all on the left . -             returnLowestcommonancestor (root->Left , p, q); -         Else            //all on the right . -             returnLowestcommonancestor (root->Right , p, q); +     } -};
AC Code

Leetcode Lowest Common Ancestor of a Binary Search Tree (LCA recent public ancestor)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.