Leetcode 94. 二叉树的中序遍历

204 阅读1分钟

Leetcode 94. 二叉树的中序遍历

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

1、题目📑

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

实例1

img

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

输出:[1,3,2]

实例2

输入:root = []

输出:[]

实例3

输入:root = [1]

输出:[1]

实例4

img

输入:root = [1,2]

输出:[2,1]

实例5

img

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

输出:[1,2]

限制

  • 树中节点数目在范围 [0, 100]
  • -100 <= Node.val <= 100

2、思路🧠

方法一

  1. 中序遍历,左,根,右。首先对树以根为基准,一直往左搜索,直到扫描到空为止。
  2. 需要注意的是当根节点为叶子节点也就是该根节点没有子节点,弹出左节点、根节点,才会来到右孩子,从而实现中序遍历。

废话少说~~~~~上代码!

3、代码👨‍💻

第一次commit AC

/**
 * Definition for a binary tree node.
 * public 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;
 *     }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return new ArrayList<Integer>();
        if(root != null) {
            Stack<TreeNode> s = new Stack<>();
            while(!s.isEmpty() || root != null) {
                if(root != null) {
                    s.push(root);
                    root = root.left;
                }else {
                    root = s.pop();
                    list.add(root.val);
                    root = root.right;
                }
            }
        }
        return list;
    }
}

时间复杂度:O(N ) 其中 N 为二叉树节点的个数。二叉树的遍历中每个节点会被访问一次且只会被访问一次。

空间复杂度:O(N) 空间复杂度取决于栈深度,而栈深度在二叉树为一条链的情况下会达到 O(n) 的级别。

image-20220322184445800

4、总结

该题目的是对树结构的理解与遍历,需要掌握先序、中序、后序的基本概念以及遍历。

树的先序、中序、后序模板:

package com.cz.Tree;

import java.util.Stack;

/**
 * @ProjectName: Data_structure
 * @Package: com.cz.Tree
 * @ClassName: UnRecursiveTraversalTree
 * @Author: 张晟睿
 * @Date: 2022/3/20 16:06
 * @Version: 1.0
 */
public class UnRecursiveTraversalTree {
    public static void main(String[] args) {
        Node1 head = new Node1(1);
        head.left = new Node1(2);
        head.right = new Node1(3);
        head.left.left = new Node1(4);
        head.left.right = new Node1(5);
        head.right.left = new Node1(6);
        head.right.right = new Node1(7);

        pre(head);
        System.out.println("========");
        middle(head);
        System.out.println("========");
        post(head);
        System.out.println("========");
    }
    public static class Node1 {
        public int value;
        public Node1 left;
        public Node1 right;

        public Node1(int val) {
            value = val;
        }
    }

    public static void pre(Node1 head) {
        System.out.println("先序遍历:");
        Stack<Node1> s = new Stack<>();
        if(head != null) {
            s.push(head);
            while(!s.isEmpty()) {
               Node1 node = s.pop();
                System.out.print(node.value + " ");
                if(node.right != null) s.push(node.right);
                if(node.left != null) s.push(node.left);
            }
        }
        System.out.println();
    }

    public static void middle(Node1 head){
        System.out.println("中序遍历:");
        if (head != null) {
            Stack<Node1> s = new Stack<>();
            while(!s.isEmpty() || head != null) {
                //步骤1:如果头结点不为空的话,一直向左边执行
                if (head != null) {
                    s.push(head);
                    head = head.left;
                }else {//根节点打印后,来到右树,继续执行步骤1
                    head = s.pop();
                    System.out.print(head.value + " ");
                    head = head.right;
                }
            }
            System.out.println();
        }
    }

    public static void post(Node1 head){
        System.out.println("后序遍历:");
        if(head != null) {
            Stack<Node1> s = new Stack<>();
            s.push(head);
            Node1 c = null; //指向栈顶的某个元素的位置
            while(!s.isEmpty()) {
                c = s.peek();
                //判断c左孩子 是否已经处理过
                if(c.left != null && head != c.left && head != c.right) {
                    s.push(c.left);
                    //判断c右孩子 是否已经处理过
                }else if(c.right != null && head != c.right) {
                    s.push(c.right);
                }else {
                    System.out.print(s.pop().value+" ");
                    head = c;   //head用来记录上次打印的内容
                }
            }
            System.out.println();
        }
    }
}

❤️‍来自专栏《LeetCode基础算法题》欢迎订阅❤️‍

厂长写博客目的初衷很简单,希望大家在学习的过程中少走弯路,多学一些东西,对自己有帮助的留下你的赞赞👍或者关注➕都是对我最大的支持,你的关注和点赞给厂长每天更文的动力。

对文章其中一部分不理解,都可以评论区回复我,我们来一起讨论,共同学习,一起进步!

原题链接:94. 二叉树的中序遍历 - 力扣(LeetCode)