没有达到预期的效果

问题描述 投票:0回答:1
from typing import List
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
       self.val = val
       self.left = left
       self.right = right
def invertTree(root):
    def reverseNode(node):
       if node == None:
          return
       reverseNode(node.left)
       reverseNode(node.right)
       temp = node.left
       node.left = node.right
       node.right = temp
    reverseNode(root)
    return root
def check(val: List[int], expected: List[int]):
    # Create the root node
    root = TreeNode()
    # Create the tree structure
    for i in range(1, len(val)):
       invertTree(val)
    actual = invertTree(root)
    # actual_list = inorderTraversal(actual)
    if actual == expected:
       print(f"Correct: input {val}, actual {actual}, and expected {expected}")
    else:
       print(f"Incorrect: input {val}, actual {actual}, and expected {expected}")


val = [4, 2, 7, 1, 3, 6, 9]
expected = [4, 7, 2, 9, 6, 3, 1]
check(val, expected)

我知道我的代码在某个地方是错误的。有人能帮我解决这个问题吗? val 是输入,expected 是输出。基本上反转二叉树并检查值。

python tree
1个回答
0
投票

您现有的代码是错误的,因为您尝试使用

invertTree(val)
将列表直接转换为二叉树,它需要 TreeNode 输入,而不是列表。

以下是需要更改的概述:

添加将列表转换为二叉树的方法:

def listToTreeNode(vals):
    # Insert your implementation here

让现有代码将列表转换为树,然后反转树:

vals = [4, 2, 7, 1, 3, 6, 9]
root = listToTreeNode(vals)  # Convert list to tree
inverted_tree_root = invertTree(root)  # Now invert the tree

来源:https://ioflood.com/blog/python-list-methods/#Troubleshooting_Common_Issues_with_Python_List_Methods

© www.soinside.com 2019 - 2024. All rights reserved.