二叉树遍历144、94、145

  • 前序遍历_迭代法
java 复制代码
public List<Integer> preorderTraversal(TreeNode root){
    List<Integer> result = new ArrayList<>();
    if(root == null) return result;
    Deque<TreeNode> stack = new ArrayDeque();
    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;
}
  • 中序遍历_迭代法
  • 思路:
  1. 将cur一直到树的最左下位置的null,再开始向result加元素。
  2. 再依次从stack取元素给cur,用cur.val给res加元素。
  3. 再cur = cur.right;//这一句代码很妙
java 复制代码
public List<Integer> inorderTraversal(TreeNode root){
    List<Integer> result = new ArrayList<>();
    if(root == null) return reault;
    Deque<TreeNode> stack = new ArrayDeque<>();
    TreeNode cur = root;
    while(cur != null || !stack.isEmpty()){
        while(cur != null){
            stack.push(cur);
            cur = cur.left;
        }
        cur = stack.pop();
        reault.add(cur.val);
        cur = cur.right;
    }
}
  • 后序遍历_迭代法
java 复制代码
oublic List<Integer> postorderTraversal(TreeNode root){
    List<Integer> result = new ArrayList<>();
    if(root == null) return result;
    Deque<TreeNode> stack = new ArrayDeque<>();
    stack.push(root);
    Deque<Integer> outputStack = new ArrayDeque<>();
    while(!stack.isEmpty()){
        TreeNode node = stack.pop();
        outputStack.push(node.val);
        // 这个左右顺寻保持和result(左-右)一样
        if(node.left != null) stack.push(node.left);
        if(node.right != null) stack.push(node.right);
    }
    while(!outputStack.isEmpty()){
        result.add(outputStack.pop());
    }
    return result;
}

总结:前序、后序的前四行代码完全一样,后序多定义了一个outputStack

相关推荐
Han.miracle12 分钟前
JavaEE-- 网络编程 http请求报头
运维·服务器·网络·网络协议·计算机网络·http
鹿鸣天涯35 分钟前
使用VMware Workstation 17虚拟机安装红帽企业版系统RHEL10
linux·运维·服务器
SKYDROID云卓小助手36 分钟前
三轴云台之控制协同技术
服务器·网络·图像处理·人工智能·算法
艾莉丝努力练剑1 小时前
【Git:企业级开发模型】Git企业级Git工作流实战:基于Git Flow的分支模型与开发流程
服务器·git·ubuntu·gitee·centos·powershell·企业级开发模型
杰 .1 小时前
Linux yum_and_apt
linux·服务器
南棱笑笑生1 小时前
20251129给荣品RD-RK3588开发板跑Rockchip的原厂Buildroot【linux-6.1】系统时适配AP6275P的蓝牙BLE
linux·运维·服务器·rockchip
Brown.alexis2 小时前
docker安装redis7
运维·docker·容器
c***21292 小时前
ubuntu 安装 Redis
linux·redis·ubuntu
u***32432 小时前
Mysql官网下载Windows、Linux各个版本
linux·数据库·mysql