Lowest Common Ancestor of a Binary Search tree Java Leetcode__java

Source: Internet
Author: User

Given A binary search tree (BST), and find the lowest common ancestor (LCA) of two Given, the BST.

According to the definition of LCA in Wikipedia: "The lowest common ancestor is defined between the two nodes V and W as the L Owest node in T so has both V and W as descendants (where we allow a node to be a descendant of itself). "

    _______6______
   /              \
___2__          ___8__

/ \ / \
0 _4 7 9
/ \
3 5
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA the nodes 2 and 4 are 2, since a node can be a descendant of itself of the LCA definition.

This topic is relatively simple, directly on the code:

public class Solution {public TreeNode lowestcommonancestor (TreeNode root, TreeNode p, Treen
        Ode q) {if (p.val==q.val) return p;
        if (P.val>q.val) return Lowestcommonancestor (ROOT,Q,P); if (root.val==p.val| | root.val==q.val| |
            (Root.val>p.val&&root.val<q.val))
        return root;
        if (Root.val<p.val) return Lowestcommonancestor (ROOT.RIGHT,P,Q);
    else return Lowestcommonancestor (ROOT.LEFT,P,Q); }
}

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.