来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
描述
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
题解
递归
class Solution {List<Integer> list = new ArrayList<>();public List<Integer> preorderTraversal(TreeNode root) {if (root == null) {return list;}list.add(root.val);if (root.left != null) {preorderTraversal(root.left);}if (root.right != null) {preorderTraversal(root.right);}return list;}}
迭代
class Solution {public List<Integer> preorderTraversal(TreeNode root) {LinkedList<TreeNode> stack = new LinkedList<>();LinkedList<Integer> res = new LinkedList<>();if (root == null) {return res;}stack.add(root);while (!stack.isEmpty()) {TreeNode node = stack.removeLast();res.add(node.val);if (node.right != null) {stack.add(node.right);}if (node.left != null) {stack.add(node.left);}}return res;}}
复杂度分析
- 时间复杂度:访问每个节点恰好一次,时间复杂度为
,其中
是节点的个数,也就是树的大小。
- 空间复杂度:取决于树的结构,最坏情况存储整棵树,因此空间复杂度是
。
