leetcode-5.10[965. 單值二叉樹、242. 有效的字母異位詞、*236. 二叉樹的最近公共祖先](python實現)

題目1

在這裏插入圖片描述

題解1

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isUnivalTree(self, root: TreeNode) -> bool:
        if root is None:
            return True
        if root.left and root.val != root.left.val:
            return False
        if root.right and root.val != root.right.val:
            return False 
        return self.isUnivalTree(root.right) and self.isUnivalTree(root.left)

附上題目鏈接

題目2

在這裏插入圖片描述

題解2

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        """
            方法一,遍歷替換
        """
        # 判斷長度是否相等
        if len(s) != len(t):
            return False
        for word in s:
            t = t.replace(word,'',1)
        return len(t) == 0

        
        """
            方法二, 哈希表
        """
        from collections import Counter
        s = Counter(s)
        t = Counter(t)
        return s == t

        """
            方法三,排序
        """
        return sorted(s) == sorted(t)

附上題目鏈接

題目3

在這裏插入圖片描述

題解3

# 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':
        """
            思路:由於是普通的二叉樹,只能用搜索的辦法,即前序遍歷法
            1. 當root就是p或者q的時候,最近公共祖先就是root;
            2. 當root爲空時,返回root;
            3. 當p,q同時出現在root的左右子樹時,那麼root就是最近的公共祖先;
            4. 當p,q在root的左子樹,那麼root.left
            5. 當p,q在root的右子樹,那麼root.right
        """
        if root is None or root is p or root is q:
            return root
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)
        # 判斷p,q那一邊
        if not left:
            return right
        if not right:
            return left
        return root

附上題目鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章