首页 > 其他分享 >leetcode - 94. 二叉树的中序遍历

leetcode - 94. 二叉树的中序遍历

时间:2022-11-03 15:12:03浏览次数:70  
标签:TreeNode cur 中序 pop stack 二叉树 null root leetcode

94. 二叉树的中序遍历

        List<Integer> inorder = new ArrayList<>();
        
        public List<Integer> inorderTraversal(TreeNode root) {
            withStack(root);
            return inorder;
        }

        //递归
        public void process(TreeNode root){
            if(root == null){
                return;
            }
            process(root.left);
            inorder.add(root.val);
            process(root.right);
        }

        //迭代
        public void withStack(TreeNode root) {
            if(root == null){
                return;
            }
            Deque<TreeNode> stack = new LinkedList<>();
            TreeNode cur = root;
            while(cur != null || !stack.isEmpty()){
                //不断往左子树方向走,每走一次就将当前节点保存到栈中
                //这是模拟递归的调用
                if(cur != null){
                    stack.push(cur);
                    cur = cur.left;
                //当前节点为空,说明左边走到头了,从栈中弹出节点并保存
                //然后转向右边节点,继续上面整个过程
                }else{
                    TreeNode pop = stack.pop();
                    inorder.add(pop.val);
                    cur = pop.right;
                }
            }
        }

 

标签:TreeNode,cur,中序,pop,stack,二叉树,null,root,leetcode
From: https://www.cnblogs.com/phonk/p/16854501.html

相关文章

  • 代码随想录第二十三天 | 二叉树终章
    今天终于是二叉树的最后一章了,三道题,加油!669.修剪二叉搜索树classSolution{publicTreeNodetrimBST(TreeNoderoot,intlow,inthigh){if(root=......
  • leetcode257-二叉树的所有路径
    257.二叉树的所有路径 泪目,自己写出的递归遍历./***Definitionforabinarytreenode.*structTreeNode{*intval;*TreeNode*left;*......
  • leetcode88
    合并两个有序数组Category Difficulty Likes Dislikesalgorithms Easy(52.02%) 1623 -TagsCompanies给你两个按非递减顺序排列的整数数组nums1和nums2,另有两个......
  • leetcode - 617. 合并二叉树
    617.合并二叉树classSolution{//迭代publicTreeNodemergeTreesWithStack(TreeNoderoot1,TreeNoderoot2){//如果当前root左右子树有一个是空......
  • LeetCode221. 最大正方形-中等(Go版)
    前情提示Go语言学习者,为了便于阅读和整理,本文代码已开源放在:https://github.com/honlu/GoDailyCodehttps://gitee.com/dreamzll/GoDailyCode持续更新中,已经完成排序算......
  • Leetcode第1668题:最大重复子字符串(Maximum repeating subarray)
    解题思路题目条件字符串长度不超过100,直接从大到小枚举word的重复次数k,判断word重复次数后是否还是sequence的字串,是就直接返回重复次数k。核心代码如下:classSolution......
  • 力扣 二叉树 算法+题目 整理
    二叉树基础包括三种遍历,建树和遍历的方法。二叉树遍历力扣144,94,145二叉树前中后序遍历使用递归或者迭代空间复杂度都是o(n),而通过morris遍历则可以达到o(1),其介绍......
  • leetcode-1880-easy
    CheckifWordEqualsSummationofTwoWordsThelettervalueofaletterisitspositioninthealphabetstartingfrom0(i.e.'a'->0,'b'->1,'c'->2,et......
  • leetcode-566-easy
    ReshapetheMatrixInMATLAB,thereisahandyfunctioncalledreshapewhichcanreshapeanmxnmatrixintoanewonewithadifferentsizerxckeepingits......
  • LeetCode刷题记录.Day4
    移除链表元素题目链接203.移除链表元素-力扣(LeetCode)classSolution{public:ListNode*removeElements(ListNode*head,intval){ListNode*varHe......