力扣刷题归纳
2024/2/20 二叉树的中序遍历
代码
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<Integer>(); // 创建一个用于存储遍历结果的列表
inorder(root,res); // 调用inorder方法进行中序遍历
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); // 再递归遍历右子树
}
}
这个和学习时讲过的二叉树写法有区别,此处用了一个链表来储存,以便于输出,但都是递归遍历
827

被折叠的 条评论
为什么被折叠?



