94.二叉树的中序遍历

一、递归

java 复制代码
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new Arraylist <> ();//结果列表
        Stack<TreeNode> stack =new Stack <> (); //栈
        TreeNode cur = root ; //指向当前节点
        while (cur! = null ||!stack.isEmpty() ){
            if (cur !=null) {
                stack.push(cur);
                cur = cur.left;// 指向左子树
            }
        else {
            cur = stack.pop();//当前节点为空说明已经到最左侧 弹出上一个根节点
            list.add(cur.val);//添加到结果list中
            cur = cur.right;//指向右子树 
        }
        }
        return list ;
    }
}

二、遍历

java 复制代码
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList <Integer> ();
        inorder (root , res);
        return res ;
    }
    public void inorder(TreeNode root ,List<Integer> res){
        if (root == null){
            return ;
        }
        inorder(root.left , res);
        res.add(root.val);
        inorder(root.right ,res);

    }

}
相关推荐
小羊没烦恼!16 小时前
微服务化的基石——持续集成
java·大数据·word·powerpoint·.net
俊昭喜喜里16 小时前
java中的继承和多态的区别
java
小羊没烦恼!16 小时前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
譕痕17 小时前
JSONObject与JSONArray封装数据格式区别
java·json
胡写代码17 小时前
别再前后端各写一套表单校验了
java·后端
小鱼能吃糖17 小时前
缺陷修复总览 · mall电商项目:5类缺陷,1个病根,4个业务域
java·电商
此时不提桶,更待何时17 小时前
01-06-A-JVM排查实战详解
java·jvm
vipxieliang18 小时前
ValidX 在 DDD 领域驱动设计中的实践
java·spring boot
ba_pi18 小时前
mysql 查询所有表名并授权
java
ProcessOn官方账号18 小时前
java函数式编程--入门基础
java·编程·函数式编程