对于二叉树的三种遍历方式,无论是简单的递归写法,还是迭代写法,都是在面试中容易被考到的,所以这篇文章就把这个常考知识点给解释清楚。
1.二叉树的前序遍历(LeetCode 144题)
前序遍历的关键在于:先遍历根节点,再遍历左子树,再遍历右子树。
即:根→左→右
(1) 递归写法
对于递归写法大家肯定都是非常清楚的,因为它的代码很简单,也比较容易理解,如下:
class Solution {
List<Integer> res = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
if(root == null) return res;
dfs(root);
return res;
}
public void dfs(TreeNode root){
if(root == null) return ;
res.add(root.val); //先遍历根节点
dfs(root.left); //再遍历左子树
dfs(root.right); //再遍历右子树
}
}
(2) 迭代写法
要把递归写法改成迭代写法,需要用到的一个很重要的数据结构:栈,用它来保存我们上一个结点,也就是记录我们从哪里来,这样在处理完某个结点的时候,我们可以通过栈来倒退回上一步,这就是迭代写法的核心。
代码如下:
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack