MySQL忘記root密碼時找回密碼方法
阿新 • • 發佈:2020-12-29
# 找兩個節點的最近的公共祖先 # 假設兩個節點 node1 和 node2,那麼最近公共祖先和node1、node2存在以下關係: # 1、node1,node2分別在祖先左右兩側 # 2、祖先是node1,node2在祖先左/右側 # 3、祖先是node2,node1在祖先左/右側 # 使用dfs深度優先遍歷進行求解 # 定義一顆二叉樹 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # 根據list建立二叉樹 def listcreattree(root, llist, i): if i < len(llist): if llist[i] == '#': return None else: root = TreeNode(llist[i]) root.left = listcreattree(root.left, llist, 2 * i + 1) root.right = listcreattree(root.right, llist, 2 * i + 2) return root return root class Solution: def nearest_common_ancestor(self, root, node1, node2): if not root: return None if root.val == node1 or root.val == node2: return root.val left = self.nearest_common_ancestor(root.left, node1, node2) right = self.nearest_common_ancestor(root.right, node1, node2) if left is not None and right is not None: return root.val if left is None: return right if right is None: return left return None if __name__ == '__main__': test_list = [3, 5, 1, 6, 2, 0, 8, '#', '#', 7, 4] root = listcreattree(None, test_list, 0) tmp1 = Solution() print(tmp1.nearest_common_ancestor(root, 5, 1)) # 結果為 3