首页 > 编程语言 > 详细

235. Lowest Common Ancestor of a Binary Search Tree java solutions

时间:2016-07-13 11:50:37      阅读:242      评论:0      收藏:0      [点我收藏+]

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

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that 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 of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

 

Subscribe to see which companies asked this question

p和q的LCA是恰好把p、q分叉的节点,也就是LCA的值介于p、q之间

从最高层的祖先root开始往下,

若不满足LCA条件,往p、q所在子树递归。

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
12         if((p.val - root.val)*(root.val - q.val) >= 0) return root;
13         return root.val > p.val ? lowestCommonAncestor(root.left,p,q) : lowestCommonAncestor(root.right,p,q);
14     }
15 }

解法二 非递归:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
12         while(root != null){
13             if(root.val > p.val && root.val > q.val) root = root.left;
14             else if(root.val < p.val && root.val < q.val) root = root.right;
15             else return root;
16         }
17         return root;
18     }
19 }

 

235. Lowest Common Ancestor of a Binary Search Tree java solutions

原文:http://www.cnblogs.com/guoguolan/p/5666123.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!