(二刷)代码随想录第14天|二叉树的递归遍历

二叉树的递归遍历

前序遍历:

递归三部曲:

1、确定参数和返回值:传入list来存放节点,返回值为void:

java 复制代码
public void preorder(TreeNode root, List<Integer> result)

2、确定终止条件:

java 复制代码
if(root == null){
    return;
}

3、确定单层递归的逻辑:

java 复制代码
result.add(root.val);
preorder(root.left, result);
preorder(root.right, result);

综合代码:

java 复制代码
public List<Integer> preorderTraversal(TreeNode root){
    List<Integer> result = new ArrayList<Integer>();
    preorder(root, result);
    return result;
}

public void preorder(TreeNode root, List<Integer> result){
    if(root == null){
        return;
    }
    result.add(root.val);
    preorder(root.left, result);
    preorder(root.right, result);


}

中序遍历:

java 复制代码
// 中序遍历·递归·LC94_二叉树的中序遍历
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        inorder(root, res);
        return res;
    }

    void inorder(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }
        inorder(root.left, list);
        list.add(root.val);             // 注意这一句
        inorder

后序遍历:

java 复制代码
// 中序遍历·递归·LC94_二叉树的中序遍历
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        inorder(root, res);
        return res;
    }

    void inorder(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }
        inorder(root.left, list);
        list.add(root.val);             // 注意这一句
        inorder

迭代法:

java 复制代码
class Solution{
    public List<Integer> preorderTraversal(TreeNode root){
        List<Integer> result = new ArrayList<>();
        if(root == null){
            return result;
        }
        
    }

    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);
    
    while(!stack.isEmpty){
        TreeNode node = stack.pop();
        result.add(node.val);
        
        if(node.right != null){
            stack.push(node.right);
        }
        
        if(node.left != null){
            stack.push(node.left);
        }
    }
    return result;
}
相关推荐
YikNjy8 分钟前
string(c++)
java·服务器·c++
呉師傅14 分钟前
联想ideapad 310-15ABR拔掉充电器使用电池工作花屏问题的解决方法【维修个例】
运维·服务器·网络·智能手机·电脑
农民小飞侠21 分钟前
SandboxFusion搭建教程
linux·ubuntu
晚风吹红霞44 分钟前
Vim编辑器从入门到熟练 —— 三种模式与常用命令详解
linux·编辑器·vim
代码熬夜敲Q1 小时前
Nginx相关
运维·服务器·nginx
土星云SaturnCloud1 小时前
基于铁塔基站的反无人机系统应用场景分析:边缘计算重构低空防御体系
服务器·人工智能·ai·边缘计算
古月方枘Fry1 小时前
OSPF 企业级多区域网络
运维·服务器·网络
gwjcloud1 小时前
Kubernetes从入门到精通(devops)06
运维·devops
shandianchengzi1 小时前
【记录】Claude Code|Ubuntu26给Claude Code新增任务消息提示音
运维·服务器·ubuntu·ai·大模型·音频·claude
蚰蜒螟1 小时前
从mkdir命令到磁盘:Linux内核目录创建过程深度解析
linux·运维·数据库