标签:
#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