【LeetCode】94. 二叉树的中序遍历

简介: 【LeetCode】94. 二叉树的中序遍历

题目描述


难度:【简单】


标签:【二叉树】


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


题目地址:https://leetcode-cn.com/problems/binary-tree-inorder-traversal/


示例


示例 1:


1268169-20211127100758854-1635826425.png


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


示例 2:


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


示例 3:


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


示例 4:


1268169-20211127100912346-91614303.png


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


示例 5:


1268169-20211127100931509-915980247.png


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


题目大意


原生的二叉树中序遍历用法。


回顾下之前的笔记:【二叉树的遍历,前序、中序和后序】


https://www.cnblogs.com/pingguo-softwaretesting/p/14615248.html


解题


二叉树的中序遍历:按照访问左子树——根节点——右子树的方式遍历这棵树,而在访问左子树或者右子树的时候我们按照同样的方式遍历,直到遍历完整棵树。


/**
 * 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> result = new ArrayList<>();
        infixOrder(root, result);
        return result;
    }
    public void infixOrder(TreeNode root, List<Integer> result) {
        if (root == null) {
            return;
        }
        // 左子树递归
        infixOrder(root.left, result);
        result.add(root.val);
        // 右子树递归
        infixOrder(root.right, result);
    }
}
相关文章
|
12天前
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
|
19天前
|
算法 API DataX
二叉树(下)+Leetcode每日一题——“数据结构与算法”“对称二叉树”“另一棵树的子树”“二叉树的前中后序遍历”
二叉树(下)+Leetcode每日一题——“数据结构与算法”“对称二叉树”“另一棵树的子树”“二叉树的前中后序遍历”
|
19天前
|
算法 DataX
二叉树(中)+Leetcode每日一题——“数据结构与算法”“剑指Offer55-I. 二叉树的深度”“100.相同的树”“965.单值二叉树”
二叉树(中)+Leetcode每日一题——“数据结构与算法”“剑指Offer55-I. 二叉树的深度”“100.相同的树”“965.单值二叉树”
|
21天前
|
算法
【力扣】94. 二叉树的中序遍历、144. 二叉树的前序遍历、145. 二叉树的后序遍历
【力扣】94. 二叉树的中序遍历、144. 二叉树的前序遍历、145. 二叉树的后序遍历
|
2月前
leetcode热题100.二叉树中的最大路径和
leetcode热题100.二叉树中的最大路径和
18 0
|
2月前
leetcode热题100. 二叉树的最近公共祖先
leetcode热题100. 二叉树的最近公共祖先
21 0
|
2月前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
2月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
2月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3
|
2月前
|
容器
《LeetCode》——LeetCode刷题日记1
《LeetCode》——LeetCode刷题日记1

热门文章

最新文章