leet code 236 二叉树最近公共节点
要找到p和q的最近公共节点,需要找到p,q节点。从根节点开始遍历,如果左子树,右子树中均可以找到p,q节点中的一个,那么当前节点即是最近根节点,如果在某一边子树中,则另一边子树返回None,在另一边子树中继续搜索,搜索终止的条件是找到某一节点或到尽头,并返回终点节点。
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root == None or root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left == None:
return right
if right == None:
return left
return root
leet code 235二叉搜索树最近公共节点
对于二叉搜索树,可以利用其性质。二叉搜索树中,左子树的值均小于等于根节点,右子树的值均大于等于根节点,所以可以通过和根节点比较大小,如果p,q的值在根节点值的两边,则当前节点为最近公共节点,若在某一边,则继续向下寻找。可以写成递归形式,或者非递归形式。
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root.val > p.val and root.val > q.val:
return self.lowestCommonAncestor(root.left, p, q)
if root.val < p.val and root.val < q.val:
return self.lowestCommonAncestor(root.right, p, q)
return root
非递归写法
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
while root:
if p.val < root.val and q.val < root.val:
root = root.left
elif p.val > root.val and q.val > root.val:
root = root.right
else:
return root