如以下代码所示,如果不在inorder前面加一个Solution是没法调用成功的,会提示函数inorder没有定义
# 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 inorder(root, list):
if root == None:
return
Solution.inorder(root.left, list)
list.append(root.val)
Solution.inorder(root.right, list)
def inorderTraversal(self, root: TreeNode) -> List[int]:
list = []
Solution.inorder(root, list)
return list
还有一种方式就是把inorder写在inorderTraversal里面:
# 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 inorderTraversal(self, root: TreeNode) -> List[int]:
def inorder(root, list):
if root == None:
return
inorder(root.left, list)
list.append(root.val)
inorder(root.right, list)
list = []
inorder(root, list)
return list
参考资料:
https://blog.csdn.net/weixin_42124234/article/details/90317389