(二刷)代码随想录第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;
}
相关推荐
vortex521 分钟前
Shell脚本技巧:去除文件中字符串两端空白
linux·bash·shell·sed·awk
world-wide-wait1 小时前
python高级04——网络编程
linux·服务器·网络
迎風吹頭髮1 小时前
Linux内核架构浅谈26-Linux实时进程调度:优先级反转与解决方案
linux·服务器·架构
Java 码农1 小时前
CentOS 7上安装SonarQube10
linux·centos
特种加菲猫1 小时前
网络协议分层:解密TCP/IP五层模型
linux·网络·笔记
等风来不如迎风去1 小时前
用你本地已有的私钥(private key)去 SSH 登录远程 Ubuntu 服务器
服务器·ubuntu·ssh
平平无奇。。。1 小时前
版本控制器之Git理论与实战
linux·git·gitee·github
tomcsdn411 小时前
SMTPman高效稳定的smtp服务器使用指南解析
服务器·邮件营销·外贸开发信·邮件群发·域名邮箱·邮件服务器·红人营销
宇宙第一小趴菜1 小时前
11 安装回忆相册
linux·运维·centos7·yum·回忆相册·kh_mod
艾莉丝努力练剑1 小时前
【Linux指令 (二)】不止于入门:探索Linux系统核心与指令的深层逻辑,理解Linux系统理论核心概念与基础指令
linux·服务器·数据结构·c++·centos