leetcode94.二叉树的中序遍历

leetcode94.二叉树的中序遍历

题目

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

用例

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

求解

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var inorderTraversal = function(root) {
    let res =[]
    mid(root)
    return res

    function mid(root){
        if(root==null){
            return
        }
        mid(root.left)
        res.push(root.val)
        mid(root.right)
    }
};
posted @ 2021-11-20 10:45  BONiii  阅读(25)  评论(0)    收藏  举报