LeetCode-94-二叉树的中序遍历

题目:

给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。

解法一: 递归写法

思路: 先处理左子树 inOrder(root.left),在打印root的值,之后处理右子树。

public static void inOrder(TreeNode root){
        if (root == null){
            return;
        }
        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);
    }

解法二: 用栈改造中序递归

注意:二叉树的先,中,后序遍历都可以用栈来改造成非递归写法。
用栈改造中序递归的基本思路就是,一路向下查找节点的左孩子,如果有左孩子,入栈,这样的话,可以保证最后一个左孩子先出栈,如果某一节点左孩子为空,pop出上一个左孩子并处理,之后对右孩子也执行相同的操作。

public List<Integer> inorderTraversal(TreeNode root) {
        if(root == null){
            return new ArrayList<Integer>();
        }
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while(!stack.isEmpty() || root != null){
            if(root != null){
                stack.push(root);
                root = root.left;
            }else{
                root = stack.pop();
                res.add(root.val);
                root = root.right;
            }
        }
        return res;
    }

如果想看二叉树的全部递归与非递归代码,请点击:二叉树的递归与非递归遍历方式

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2024-04-22 20:40:03       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-22 20:40:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-22 20:40:03       20 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-22 20:40:03       20 阅读

热门阅读

  1. springboot接口提高查询速度方法

    2024-04-22 20:40:03       14 阅读
  2. 分治法构建Gray码问题

    2024-04-22 20:40:03       13 阅读
  3. 深入理解与运用Vue 2中的插槽(Slots)

    2024-04-22 20:40:03       13 阅读
  4. 测试testing1

    2024-04-22 20:40:03       14 阅读
  5. Mysql多表联查使用聚合函数常见问题

    2024-04-22 20:40:03       14 阅读
  6. 第七周笔记

    2024-04-22 20:40:03       11 阅读
  7. MySQL运维故障排查与高效解决方案

    2024-04-22 20:40:03       15 阅读
  8. 机器学习笔记 - torch.hub 和 torchvision.models 的区别

    2024-04-22 20:40:03       12 阅读
  9. MySQL运维故障解决方案:实战案例与深度解析

    2024-04-22 20:40:03       12 阅读
  10. JWT原理

    JWT原理

    2024-04-22 20:40:03      14 阅读
  11. Docker - 网络

    2024-04-22 20:40:03       14 阅读
  12. MySQL无法远程连接方案解决(示例)

    2024-04-22 20:40:03       13 阅读
  13. 卸载jenkins和docker

    2024-04-22 20:40:03       13 阅读
  14. 算法=问题的解决方法

    2024-04-22 20:40:03       17 阅读
  15. Unity中Socket,Tcp,Udp网络连接协议总结

    2024-04-22 20:40:03       14 阅读
  16. 浅谈薪酬绩效设计及运行的忌讳

    2024-04-22 20:40:03       17 阅读
  17. ubuntu用户与用户组管理

    2024-04-22 20:40:03       14 阅读