题解 | #二叉树的前序遍历#
二叉树的前序遍历
https://www.nowcoder.com/practice/5e2135f4d2b14eb8a5b06fab4c938635
from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def preorderTravelsal(root: TreeNode) -> TreeNode: lists = [] preorder(lists, root) return lists def preorder(list: List[int], root: TreeNode): if root == None: return None # 先遍历根节点 list.append(root.val) # 再去左子树 preorder(list, root.left) # 再去右子树 preorder(list, root.right) if __name__ == '__main__': # lists = input().split(',') root = TreeNode(1) root.left = None root.right = TreeNode(2) root.right.left = TreeNode(3) result = preorderTravelsal(root) print(result)