【问题标题】:How to check if tree is symmetric python如何检查树是否是对称的python
【发布时间】:2019-07-04 06:33:52
【问题描述】:

为了练习,我解决了 Leetcode 101. Symmetric Tree 的问题:

给定一棵二叉树,检查它是否是自身的镜像(即围绕其中心对称)。

我有一个想法要做顺序遍历,将每个节点值记录到列表中并检查第一部分的值,然后从列表中反转第二部分。但 它在测试用例 [1,2,3,3,null,2,null] 上失败了 从我的本地,我的值返回 [3, 2, None, 1, 2, 3, None],但从 leetcode 返回 [3,2,1,2,3] 有人知道我的代码有什么问题吗?

def isSymmetric(root: 'TreeNode') -> 'bool':

    if not root: return True
    value = []

    def traversal(cur):
        if cur:
            traversal(cur.left)
            value.append(cur.val)
            traversal(cur.right)

    traversal(root)
    size = int(len(value) / 2)
    return value[:size] == value[size + 1:][-1::-1]

【问题讨论】:

  • 看来你的本地树与 leetcode 使用的树不匹配。您的本地树是否包含带有self.val is None 的节点?
  • 是的......但请参考@Kevin He 的回答。我错了,中序遍历无法确定树是否对称

标签: python-3.x algorithm binary-tree


【解决方案1】:

恐怕中序遍历不能唯一确定一棵树。例如一棵有结构的树

1
 \
  2
   \
    3

有同样的中序遍历
  2
 / \
1   3

由于您有if cur 条件,因此您的中序遍历将不包括空节点,这使得遍历不唯一。您可以像这样包含空节点:

 def traverse(cur):
     if cur:
         traverse(cur.left)
     values.append(cur.val if cur else None)
     if cur:
         traverse(cur.right)

这将唯一地序列化树节点。

你还可以在这种情况下确定左节点和右节点的结构相同(除了左右颠倒)。这是我接受的解决方案:

class Solution:
    def isSymmetric(self, root: 'TreeNode') -> 'bool':
        if not root:
            return True
        return self.isSymmetricHelper(root.left, root.right)

    def isSymmetricHelper(self, node1, node2):
        if node1 is None and node2 is None:
            return True
        if node1 is None or node2 is None:
            return False
        if node1.val != node2.val: # early stopping - two nodes have different value
            return False 
        out = True
        out = out and self.isSymmetricHelper(node1.left, node2.right)
        if not out: # early stopping
            return False
        out = out and self.isSymmetricHelper(node1.right, node2.left)
        return out

它递归地检查两棵树是否是彼此的镜像(有一些提前停止)。这个想法是如果两棵树是镜像的,则tree1的左子树必须是tree2的右子树的镜像,同样适用于tree1的右子树和tree2的左子树。

虽然两者的运行时间都是 O(n),但递归方法占用 O(logn) 平均空间(由调用堆栈使用)并且内置提前停止,而您的 serialize-all-nodes 方法占用 O(n ) 空间 O(n) 时间。

【讨论】:

  • You can include the null nodes like this: - 这将在cur.val 上失败,因为curNone
【解决方案2】:

对称树是这样的:

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        def is_mirror(t1,t2):
            # If I reached all the way down that means I always got True.
            if t1 is None and t2 is None:
                return True
            # if one of them is None but other one is not then False
            if t1 is None or t2 is None:
                return False
            # 2=2 and t1.left==t2.right and t1.right==t2.left
            return t1.val==t2.val and is_mirror(t1.left,t2.right) and is_mirror(t1.right,t2.left)
        return is_mirror(root.left,root.right)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-05
    • 2012-01-16
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    相关资源
    最近更新 更多