题解 | #二叉树# #二叉搜索树的最近公共祖先#
二叉搜索树的最近公共祖先
https://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f
#coding:utf-8 # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param root TreeNode类 # @param p int整型 # @param q int整型 # @return int整型 # class Solution: def lowestCommonAncestor(self , root , p , q ): # write code here if root == None or p == None or q == None: return root #switch node if p < q: tmp = p p = q q = tmp ##coner case #cond1: root == p or root == q #cond2: root.val > p.val and root.val < q.val #cond3: root.val > p.val #cond4: root.val < p.val print ("root.val, p, q: ", root.val, p, q) if root.val == p: print ("ck1") return root.val elif root.val > q and root.val < p: print ("ck2") return root.val elif root.val > p: print ("ck3") return self.lowestCommonAncestor(root.left, p, q) else: print ("ck4") return self.lowestCommonAncestor(root.right, p, q) return root.val