Leetcode 235:lowest Common Ancestor of a Binary Search Tree

Source: Internet
Author: User

Lowest Common Ancestor of a Binary Search TreeTotal Accepted: 203 Total Submissions: 511

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

According to the definition of the LCA in Wikipedia: "The lowest common ancestor is defined between," nodes V and W as the L Owest node in T, have both V and W as descendants (where we allowa 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 and are 2 8 6 . Another example is LCA of nodes 2 4 2 and are, since a node can be a descendant of itself according to the LCA Definition.

Ideas

If p,q is smaller than root, the LCA must be in the left subtree, and if the p,q is larger than root, then the LCA must be in the right sub-tree. If Yidayixiao, then root is the LCA.

[CODE]

/** * Definition for a binary tree node.  * public class TreeNode {*     int val, *     TreeNode left, *     TreeNode right; *     TreeNode (int x) {val = x;} *} */public class Solution {    //2, 1 public    TreeNode lowestcommonancestor (TreeNode root, TreeNode p, TreeNode q) {
   if (root==null | | p==null | | q==null) return NULL;                if (Math.max (P.val, Q.val) < Root.val) {            return lowestcommonancestor (Root.left, p, q);        } else if (Math.min ( P.val, Q.val) > Root.val) {            return lowestcommonancestor (Root.right, p, q);        } else return root;}    }

This problem can also have a followup.  If it is an ordinary binary tree, not BST.   You should traverse the nodes to find P,q first. Also record the path from root to the points. After comparing the paths, the last of the same nodes is the LCA.

[CODE]

/** * Definition for a binary tree node.  * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *}        */public class Solution {//2, 1 public TreeNode lowestcommonancestor (TreeNode root, TreeNode p, TreeNode q) {                if (root==null | | p==null | | q==null) return NULL;        list<treenode> PATHP = new arraylist<> ();        list<treenode> PATHQ = new arraylist<> ();        Pathp.add (root);                Pathq.add (root);        GetPath (Root, p, PATHP);                GetPath (Root, Q, PATHQ);        TreeNode LCA = null; for (int i=0; I<pathp.size () && i<pathq.size (); i++) {if (Pathp.get (i) = = Pathq.get (i)) LCA = Path            P.get (i);        else break;    } return LCA; } Private Boolean GetPath (TreeNode root, TreeNode N, list<treenode> path) {if (root==n) {R        Eturn true;    } if (Root.left!=null) {        Path.add (Root.left);            if (GetPath (root.left, N, Path)) return true;        Path.remove (Path.size ()-1);            } if (Root.right!=null) {path.add (root.right);            if (GetPath (root.right, N, Path)) return true;        Path.remove (Path.size ()-1);    } return false; }}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode 235:lowest Common Ancestor of a Binary Search Tree

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.