1、验证二叉搜索树
https://leetcode-cn.com/problems/validate-binary-search-tree/description/
方法1:中序遍历,看遍历的数组是否有序。
class Solution:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
inorder = self.inorder(root)
return inorder == list(sorted(set(inorder)))
def inorder(self,root):
if root is None:
return []
return self.inorder(root.left) + [root.val] + self.inorder(root.right)
方法2:递归。设置边界low和high,左子树的值应在low和根值之间,右子树的值应在根值和high之间。算法速度快在于,若找到一条支路不符合条件,则返回False,不必再判断剩下支路。
class Solution:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.isValid(root,-2**32,2**32-1)
def isValid(self, root, low, high):
if root is None: # 搜索到叶子节点仍没有错,说明该条支路符合二叉搜索树性质
return True
if low != None and root.val<=low:
return False
if high != None and root.val>=high:
return False
return self.isValid(root.left,low,root.val) and self.isValid(root.right,root.val,high) #左右子树都符合二叉搜索树的性质才返回True
2、二叉树的最近公共祖先
class Solution:
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root is None or root.val == p.val or root.val == q.val: #若root没有子结点或根结点与要找的p,q有一个相等,则返回当前根结点
return root
l = self.lowestCommonAncestor(root.left,p,q) #查找左子树是否含p或q
r = self.lowestCommonAncestor(root.right,p,q) #查找右子树是否含p或q
if l and r : #如果root的左右子树都包含p或q,说明当前根为最近公共根
return root
if not l: #如果左子树不含p和q,返回右子树
return r
if not r: #如果右子树不含p和q,返回左子树
return l