码迷,mamicode.com
首页 > 其他好文 > 详细

Jan 12 - Lowest Common Ancestor of a Binary Search Tree; Tree; BST; Recursion;

时间:2016-01-13 07:05:18      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) return null;
        else if(p == null) return q;
        else if(q == null) return p;
        else if(p.val < q.val){
            if(root.val > p.val && root.val < q.val) return root;
            else if(root.val == p.val || root.val == q.val) return root;
            else if(root.val < p.val) return lowestCommonAncestor(root.right, p, q);
            else return lowestCommonAncestor(root.left, p, q);
        }
        else{
            if(root.val > q.val && root.val < p.val) return root;
            else if(root.val == p.val || root.val == q.val) return root;
            else if(root.val < q.val) return lowestCommonAncestor(root.right, p, q);
            else return lowestCommonAncestor(root.left, p, q);
        }
    }
}

  

Jan 12 - Lowest Common Ancestor of a Binary Search Tree; Tree; BST; Recursion;

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5126131.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!