(二刷)代码随想录第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;
}
相关推荐
迷海6 分钟前
Linux g++编译与GDB调试完整流程(文末附图)
linux·gdb调试工具·g++编译器
softbangong8 分钟前
815-批量Excel文件合并工具,批量excel文件、工作表合并软件
linux·windows·excel·文件合并·excel合并·数据整理
123过去16 分钟前
responder使用教程
linux·网络·测试工具·安全·哈希算法
不知名。。。。。。。。20 分钟前
数据链路层
linux·网络
桌面运维家24 分钟前
KVM虚拟机:快照增量备份与Linux系统快速恢复
linux·运维·服务器
charlie11451419130 分钟前
嵌入式C++教程实战之Linux下的单片机编程:从零搭建 STM32 开发工具链(2) —— HAL 库获取、启动文件坑位与目录搭建
linux·开发语言·c++·stm32·单片机·学习·嵌入式
Sarapines Programmer42 分钟前
【Docker】Windows 安装 Docker 简明指南
运维·docker·容器
cnnews1 小时前
手机通过Termux安装unbuntu,开启SSH
linux·运维·ubuntu·ssh
吴声子夜歌1 小时前
TypeScript——声明合并
linux·ubuntu·typescript
wwj888wwj1 小时前
mydumper备份数据库以及还原
linux·运维·服务器