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

相关推荐
whgjjim34 分钟前
docker迅雷自定义端口号、登录用户名密码
运维·docker·容器
tmacfrank2 小时前
网络编程中的直接内存与零拷贝
java·linux·网络
瀚高PG实验室4 小时前
连接指定数据库时提示not currently accepting connections
运维·数据库
QQ2740287564 小时前
Soundness Gitpod 部署教程
linux·运维·服务器·前端·chrome·web3
淡忘_cx4 小时前
【frp XTCP 穿透配置教程
运维
qwfys2004 小时前
How to configure Linux mint desktop
linux·desktop·configure·mint
南方以南_4 小时前
Ubuntu操作合集
linux·运维·ubuntu
冼紫菜5 小时前
[特殊字符]CentOS 7.6 安装 JDK 11(适配国内服务器环境)
java·linux·服务器·后端·centos
Chuncheng's blog6 小时前
RedHat7 如何更换yum镜像源
linux
爱莉希雅&&&6 小时前
shell脚本之条件判断,循环控制,exit详解
linux·运维·服务器·ssh