leetcode刷题笔记(python3)--144. Binary Tree Preorder Traversal

144. Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes’ values.

Example:

Input: [1,null,2,3]
1

2
/
3

Output: [1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?

有迭代和递归两种方式

func preorderTraversal(root *TreeNode) []int {
	if root == nil {
        return []int{}
	}
	res := []int{}
	preOrder(root, &res)
	return res
}

func preOrder(root *TreeNode, ans *[]int) {
	if root == nil {
		return
	}
	*ans = append(*ans, root.Val)
	preOrder(root.Left, ans)
	preOrder(root.Right, ans)
}
发布了98 篇原创文章 · 获赞 0 · 访问量 1452

猜你喜欢

转载自blog.csdn.net/weixin_44555304/article/details/104427052