class Solution {
public List<Integer>inorderTraveral(TreeNode root) {
List<Integer> res=new ArrayList<Integer>();
inorder(root,res);
return res;
}
public void inorder(TreeNode root,List<Integer>res) {
if(root==null) {
return;
}
inorder(root.left,res);
res.add(root.val);
inorder(root.right,res);
}
}
方法二:迭代
思路与算法
方法一的递归函数我们也可以用迭代的方式实现,两种方式是等价的,区别在于递归的时候隐式地维护了一个栈,而我们在迭代的时候需要显式地将这个栈模拟出来,其他都相同,具体实现可以看下面的代码。
1-024-_(LeetCode-94) 二叉树的中序遍历_哔哩哔哩_bilibili
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
// 栈 先进后出
// 前序遍历,出栈顺序:根左右; 入栈顺序:右左根
// 中序遍历,出栈顺序:左根右; 入栈顺序:右根左
// 后序遍历,出栈顺序:左右根; 入栈顺序:根右左
List<Integer> ans = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<>();
// root不为空或stack不为空,遍历继续
while (root != null || !stack.isEmpty()) {
// 先根后左入栈
while (root != null) {
stack.push(root);
root = root.left;
}
// 此时root==null,说明上一步的root没有左子树
// 1. 执行左出栈。因为此时root==null,导致root.right一定为null
// 2. 执行下一次外层while代码块,根出栈。此时root.right可能存在
// 3a. 若root.right存在,右入栈,再出栈
// 3b. 若root.right不存在,重复步骤2
root = stack.pop();
ans.add(root.val);
root = root.right;
}
return ans;
}
}
前序与中序的区别: 前序:中 左 右 中序:左中右 后序:左右中
前序遍历(思路重要)
注意第一步为后续遍历左子树。
递归
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
preorder(root, res);
return res;
}
public void preorder(TreeNode root, List<Integer> res) {
if (root == null) {
return;
}
res.add(root.val);//先放中间节点值 与中序区别
preorder(root.left, res);
preorder(root.right, res);
}
}
力扣 前中后总结
理解这个? 调用方法()里为传的参数。 调用的方法就是循环递归(因为在这个方法里面操作)