一、题目
力扣原题:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
二、递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private List<Integer> result = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
if (null == root) {
return new ArrayList<>();
}
result.add(root.val);
if (null != root.left) {
preorderTraversal(root.left);
}
if (null != root.right) {
preorderTraversal(root.right);
}
return result;
}
}
- 时间复杂度:O(n)
- 空间复杂度:
- 最优:O(log(n))。二叉树的深度最小时
- 最差:O(n)。二叉树退化为链表时
- 平均:O(log(n))
三、迭代
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
if (null == root) {
return new ArrayList<>();
}
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
stack.add(root);
while (!stack.empty()) {
// 节点出栈
TreeNode node = stack.pop();
// 添加到结果集
result.add(node.val);
// 压右节点
if (null != node.right) {
stack.add(node.right);
}
// 压左节点
if (null != node.left) {
stack.add(node.left);
}
}
return result;
}
}
- 时间复杂度:O(n)
- 空间复杂度:O(n),辅助栈
四、总结
- 二叉树的遍历方式有递归、迭代两种方式
- 迭代方式的遍历可以借助栈实现,但需要注意栈先进先出的特性