leetcode:通过倒立树解决对称树问题

发布于 2025-02-05 20:04:36 字数 1632 浏览 1 评论 0原文

我正在研究leetcode问题 101。对称树

给定二进制树的root,检查它是否是自身的镜子(即,在其中心周围对称)。

这是我的代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        org_root_list=[]
        
        def dfs(root: Optional[TreeNode]) -> None:
            if not root:
                return
            dfs(root.left)
            org_root_list.append(root.val)
            dfs(root.right)
            
        dfs(root)
        
        def invert(root: Optional[TreeNode]) -> None:
            if not root:
                return
            left, right = invert(root.left), invert(root.right)   # dfs
            root.left, root.right = root.right, root.left

        invert(root)    
        root_list=[]
        
        def dfs1(root: Optional[TreeNode]) -> None:
            if not root:
                return
            dfs1(root.left)
            root_list.append(root.val)
            dfs1(root.right)
            
        dfs1(root)
        return root_list==org_root_list

我已经通过此代码通过了195/198的测试用例。它失败的第一个测试案例是:

[1,2,2,2,null,2]
Output: True
Expected: False

倒置函数的代码反转树。 dfs函数在原始的根树上运行一个内部遍历。然后dfs1在倒立的树上进行内存遍历,它们分别附加到两个列表。然后,我们通过比较两个列表是否相同来返回结果。

I am working on LeetCode problem 101. Symmetric Tree:

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

This is my code:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        org_root_list=[]
        
        def dfs(root: Optional[TreeNode]) -> None:
            if not root:
                return
            dfs(root.left)
            org_root_list.append(root.val)
            dfs(root.right)
            
        dfs(root)
        
        def invert(root: Optional[TreeNode]) -> None:
            if not root:
                return
            left, right = invert(root.left), invert(root.right)   # dfs
            root.left, root.right = root.right, root.left

        invert(root)    
        root_list=[]
        
        def dfs1(root: Optional[TreeNode]) -> None:
            if not root:
                return
            dfs1(root.left)
            root_list.append(root.val)
            dfs1(root.right)
            
        dfs1(root)
        return root_list==org_root_list

I have passed 195/198 test cases with this code. The first test case it failed was:

[1,2,2,2,null,2]
Output: True
Expected: False

The code for the invert function inverts the tree. The dfs function runs an inorder traversal on the original root tree. And then dfs1 does an inorder traversal on the inverted tree, and they append to two lists, respectively. Then we return the result by comparing whether the two lists were same.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鯉魚旗 2025-02-12 20:04:36

如果两棵树具有相同的内顺序,则它们是相同的。例如,这些树都具有相同的内顺序序列,因此在它们上运行dfs的结果将导致相同的输出:

    2               3        1
   / \             /          \
  1   3           2            2
                 /              \
                1                3

解决此问题的一种方法是在遇到,使深度第一阶预订,而不是订购。

代码上的其他一些说明:

  • invert函数中未使用。如果事实,它们始终是,因为invert总是返回none

  • 可惜您有两个DFS函数,只是因为您需要在其他列表中的输出。将该功能变成发电机,以便呼叫者可以在所需的位置收集这些值。

导致此代码:

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        def dfs(root: Optional[TreeNode]): 
            if not root:
                yield None  # extra value for each encountered None
                return
            yield root.val  # pre-order instead of in-order
            yield from dfs(root.left)
            yield from dfs(root.right)
                    
        def invert(root: Optional[TreeNode]) -> None:
            if not root:
                return        
            invert(root.left)
            invert(root.right)
            root.left, root.right = root.right, root.left
            
        org_root_list = list(dfs(root))
        invert(root)
        return list(dfs(root)) == org_root_list

It is not true that if two trees have the same in-order sequence, they are the same. For instance, these trees all have the same in-order sequence, and so the result of running dfs on them would lead to the same output:

    2               3        1
   / \             /          \
  1   3           2            2
                 /              \
                1                3

One way to solve this, is to also produce a value when encountering None, and to make the depth first order a pre-order instead of an in-order.

Some other remarks on your code:

  • left and right are not used in the invert function. If fact, they are always None, because invert always returns None.

  • It is a pity that you have two dfs functions, just because you need the output in a different list. Turn that function into a generator, so that the caller can collect those values where they want.

That leads to this code:

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        def dfs(root: Optional[TreeNode]): 
            if not root:
                yield None  # extra value for each encountered None
                return
            yield root.val  # pre-order instead of in-order
            yield from dfs(root.left)
            yield from dfs(root.right)
                    
        def invert(root: Optional[TreeNode]) -> None:
            if not root:
                return        
            invert(root.left)
            invert(root.right)
            root.left, root.right = root.right, root.left
            
        org_root_list = list(dfs(root))
        invert(root)
        return list(dfs(root)) == org_root_list
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文