力扣练习(Python3):栈类:第144题:二叉树的前序遍历:给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,2,3]
链接:https://leetcode-cn.com/leetbook/read/data-structure-binary-tree/xeywh5/
主要方法:递归
知识点:
二叉树根节点的值:root.val
二叉树的左子树:root.left
二叉树的右子树:root.right
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
result = []
def preorder(root):
if root == None:
return result
result.append(root.val)
preorder(root.left)
preorder(root.right)
preorder(root) # 调用方法
return result