zoukankan      html  css  js  c++  java
  • 树的练习(4)

    class Solution:
        def isSymmetric(self, root: TreeNode) -> bool:
            def recur(L, R):
                if not L and not R: return True
                if not L or not R or L.val != R.val: return False
                return recur(L.left, R.right) and recur(L.right, R.left)
            return recur(root.left, root.right) if root else True
    如果上面的不容易理解,可以看下面的
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def isSymmetric(self, root: TreeNode) -> bool:
            if not root:
                return True
            def recur(L, R):
                if not L and not R: return True
                if not L or not R or L.val != R.val: return False
                return recur(L.left, R.right) and recur(L.right, R.left)
            return recur(root.left, root.right) 
    迭代
    class Solution:
        def isSymmetric(self, root: TreeNode) -> bool:
            if root is None:
                return True
            q = []
            q.append(root.left)
            q.append(root.right)
            while len(q)!=0:
                A = q.pop(0)
                B = q.pop(0)
                if A == None and B == None:
                    continue
                if A == None or B == None:
                    return False
                if A.val != B.val:
                    return False
                q.append(A.left)
                q.append(B.right)
                q.append(A.right)
                q.append(B.left)
            return True 

    将上一题。改进:

    class Solution:
        def isSymmetric_queue(self, root: TreeNode) -> bool:
            """
            辅助队列法
            """
            if not root:
                return True
            queue = [(root.left,root.right)]
            while queue:
                l, r = queue.pop(0)
                if not l and not r: # 如果左右子节点为空,跳过后面步骤
                    continue
                if not l or not r: # 如果左右子节点任意一个为空,则表示不对称
                    return False
                if l.val != r.val: # 如果左右子节点的值不等,则表示不对称
                    return False
                queue.append((l.left, r.right)) # 将左子树的左节点,和右子树的右节点放入队列
                queue.append((l.right, r.left))
            return True
  • 相关阅读:
    拉普拉斯矩阵
    正定矩阵 和 半正定矩阵
    Random Walk
    论文解读(DGI)《DEEP GRAPH INFOMAX》
    python安装easyinstall/pip出错
    pip国内源设置
    在Jupyter Notebook添加代码自动补全功能
    [BUUCTF]PWN——bjdctf_2020_babystack2
    [BUUCTF]REVERSE——[BJDCTF 2nd]8086
    [BUUCTF]PWN——jarvisoj_tell_me_something
  • 原文地址:https://www.cnblogs.com/topass123/p/12761902.html
Copyright © 2011-2022 走看看