Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes’ values.
Follow up: Recursive solution is trivial, could you do it iteratively?
Example 1
1 | Input: [1,null,2,3] |
解题思路
先根遍历,先打印根节点值,再遍历左子树,最后遍历右子树。迭代法需要用栈记录根节点作为遍历完左子树的出口,以便在遍历完左子树后,继续遍历右子树。
复杂度分析
- 时间复杂度:$O(n)$。
- 空间复杂度:$O(n)$。
代码
1 | class Solution { |