二叉树遍历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

相关推荐
fengkai45459 分钟前
十二、Redis -1
运维·数据库·redis
忆挽篱笙歌20 分钟前
gdb/cgdb
linux·ubuntu
甜到心里的蛋糕27 分钟前
Playwright 无头浏览器自动发布 CSDN 图文草稿的实践(持久化 profile + 图床直传)
运维·python·playwright·爬虫自动化·博客运营
fei_sun1 小时前
RIB、FIB、MAC 、ARP 表
服务器·网络·macos
凌云若寒1 小时前
BarTender提示#807错误:无法在拥有其他许可证的Licensing Service上激活节点锁定的 Professional 版许可证 的解决办法
运维·服务器·前端·学习·软件需求
Julien20042 小时前
管理 Ansible 配置文件
linux·运维·服务器·ssh·学习方法
逐米时代2 小时前
远程运维诊断减少到场率
java·服务器·前端
pt10432 小时前
CML网络仿真入门-6(结):Cisco Modeling Labs 示例拓扑
服务器·网络
MicrosoftCloud2 小时前
性能排查 01|free 显示内存用了 90% 就是快满了吗?buff/cache 与 available 一次讲清
linux·运维·内存·free·buff/cache
灯澜忆梦2 小时前
【docker】#1 | Docker 初识
运维·docker·容器