# 【LeetCode】每日一题144：二叉树的前序遍历

## 144.二叉树的前序遍历

public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(){}
TreeNode(int val){ this.val = val;}
TreeNode(int val, TreeNode left, TreeNode right){
this.val = val;
this.left = left;
this.right = right;
}
}


## 递归

List<Integer> res = new ArrayList<>();
public List<Integer> preorderTraversal1(TreeNode root) {
preOrder(root);
return res;
}
public void preOrder(TreeNode root) {
if (root == null) {
return;
}
preOrder(root.left);
preOrder(root.right);
}


## 迭代

List<Integer> res = new ArrayList<>();
public List<Integer> preorderTraversal2(TreeNode root) {
if(root == null) {
return res;
}
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
while (!stack.empty() || node != null) {
while (node != null) {
stack.push(node);
node = node.left;
}
node = stack.pop();
node = node.right;
}
return res;
}

public List<Integer> preorderTraversal2(TreeNode root) {
if(root == null) {
return res;
}
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
while (!stack.empty() || node != null) {
while (node != null) {
stack.push(node);
node = node.left;
}
node = stack.pop();
node = node.right;
}
return res;
}


• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

喜欢下雨所以爱上雷震子

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
06-19 1378
03-02 116

07-08 856
05-16 138
03-27 47
02-03 97