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

LeetCode#235 Lowest Common Ancestor of a Binary Search Tree

时间:2015-09-08 21:41:18      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

#235 Lowest Common Ancestor of a Binary Search Tree

寻找二叉搜索树两个节点的最小共同祖先

java代码:

/**

 * 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 || p == null || q == null){

            if(root == null)    return null;

            else if(p == null && q == null) return root;

            else return p == null?q:p;

        }

        if((root.val - p.val)*(root.val - q.val) <= 0){

            return root;

        }else if((root.val>p.val) && (root.val>q.val)){

            return lowestCommonAncestor(root.left, p, q);

        }else{

            return lowestCommonAncestor(root.right, p, q);

        }

    }

}if(root.val > bigger){

return this.lowestCommonAncestor(root.left, p, q);

}else if(root.val < smaller){

return this.lowestCommonAncestor(root.right, p, q);

}else{

return root;

}

}

}

python代码:

# Definition for a binary tree node.

# class TreeNode(object):

#     def __init__(self, x):

#         self.val = x

#         self.left = None

#         self.right = None

 

class Solution(object):

    def lowestCommonAncestor(self, root, p, q):

        """

        :type root: TreeNode

        :type p: TreeNode

        :type q: TreeNode

        :rtype: TreeNode

        """

        if not root:

            return

        if (root.val - p.val)*(root.val - q.val) <= 0:

            return root

        elif root.val > p.val and root.val > q.val:

            return self.lowestCommonAncestor(root.left, p, q)

        else:

 

            return self.lowestCommonAncestor(root.right, p, q)

LeetCode#235 Lowest Common Ancestor of a Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/kevinCK/p/4789928.html

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