栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

力扣刷题--94、二叉树的中序遍历

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

力扣刷题--94、二叉树的中序遍历

题目: 二叉树的中序遍历

题号:94

难易程度:简单

题面:

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

示例1:

输入:root = [1,null,2,3]
输出:[1,3,2]

示例2:

输入:root = []
输出:[]

示例3

输入:root = [1]
输出:[1]

题目意思:
使用中序遍历输出一个二叉树的值。

前中后序遍历:
DLR–前序遍历(根在前,从左往右,一棵树的根永远在左子树前面,左子树又永远在右子树前面 )

LDR–中序遍历(根在中,从左往右,一棵树的左子树永远在根前面,根永远在右子树前面)

LRD–后序遍历(根在后,从左往右,一棵树的左子树永远在右子树前面,右子树永远在根前面)

题解:
1、递归:先递归root.left的值,然后再递归root.right的值
2、迭代:定义一个栈,将left放入栈中,由于栈是先进后出,当left为空时,再将栈中的数据弹出,然后放入list中,最后在将right的值放入栈中进行相同操作。

public class LeetCode88 {
   public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    
    public List inorderTraversal1(TreeNode root) {
        List res  = new ArrayList<>();
        inOrder(root,res);
        return  res;
    }
    private  void inOrder(TreeNode root,List res){
        if (root == null) {
            return ;
        }
        inOrder(root.left,res);
        res.add(root.val);
        inOrder(root.right,res);
    }

    
    public List inorderTraversal(TreeNode root) {
        List res = new ArrayList<>();
        Deque stk = new linkedList();
        while (root != null || !stk.isEmpty() ){
            while (root != null){
                stk.push(root);
                root = root.left;
            }
            root =  stk.pop();
            res.add(root.val);
            root = root.right;
        }
        return  res;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/309992.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号