(二刷)代码随想录第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;
}
相关推荐
程序设计实验室28 分钟前
经历分享,发现挖矿木马后,服务器快速备份与重装(腾讯云平台)
linux
Miku162 小时前
OpenClaw-Linux+飞书官方Plugin安装指南
linux·人工智能·agent
Miku162 小时前
OpenClaw 接入 QQ Bot 完整实践指南
linux·人工智能·agent
Yogurt_cry7 小时前
[树莓派4B] 闲置近10年的爱普生 L310 打印机爆改无线打印机
linux·物联网·树莓派
爱吃橘子橙子柚子1 天前
3CPU性能排查总结(超详细)【Linux性能优化】
运维·cpu
Johny_Zhao1 天前
OpenClaw中级到高级教程
linux·人工智能·信息安全·kubernetes·云计算·yum源·系统运维·openclaw
Sheffield2 天前
Docker的跨主机服务与其对应的优缺点
linux·网络协议·docker
Sheffield2 天前
Alpine是什么,为什么是Docker首选?
linux·docker·容器
舒一笑3 天前
程序员效率神器:一文掌握 tmux(服务器开发必备工具)
运维·后端·程序员