(二刷)代码随想录第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;
}
相关推荐
迎仔4 分钟前
A-总览:GPU驱动运维系列总览
linux·运维
tiantangzhixia6 分钟前
Master PDF Linux 平台的 5.9.35 版本安装与自用
linux·pdf·master pdf
AI_56787 分钟前
阿里云OSS成本优化:生命周期规则+分层存储省70%
运维·数据库·人工智能·ai
choke23310 分钟前
软件测试任务测试
服务器·数据库·sqlserver
yyy的学习记录12 分钟前
Ubuntu下urdf模型转换成proto模型
linux·运维·ubuntu
礼拜天没时间.17 分钟前
自定义镜像制作——从Dockerfile到镜像
linux·docker·容器·centos·bash
xixingzhe217 分钟前
ubuntu安装gitlab
linux·ubuntu·gitlab
猫头虎23 分钟前
OpenClaw开源汉化发行版:介绍、下载、安装、配置教程
运维·windows·开源·aigc·ai编程·agi·csdn
强风79425 分钟前
Linux-传输层协议TCP
linux·网络·tcp/ip
那我掉的头发算什么31 分钟前
【Mybatis】Mybatis-plus使用介绍
服务器·数据库·后端·spring·mybatis