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

相关推荐
安红豆.18 分钟前
Linux基础入门 --13 DAY(SHELL脚本编程基础)
linux·运维·操作系统
..空空的人18 分钟前
linux基础指令的认识
linux·运维·服务器
penny_tcf19 分钟前
Linux基础命令halt详解
linux·运维·服务器
鱼跃鹰飞22 分钟前
Leecode热题100-295.数据流中的中位数
java·服务器·开发语言·前端·算法·leetcode·面试
N1cez39 分钟前
vscode 连接服务器 不用输密码 免密登录
服务器·vscode
杨哥带你写代码1 小时前
构建高效新闻推荐系统:Spring Boot的力量
服务器·spring boot·php
万界星空科技1 小时前
界星空科技漆包线行业称重系统
运维·经验分享·科技·5g·能源·制造·业界资讯
荣世蓥1 小时前
10.2 Linux_进程_进程相关函数
linux·运维·服务器
gma9992 小时前
【MySQL】服务器管理与配置
运维·服务器