力扣94-JS二叉树的中序遍历

https://leetcode.cn/problems/binary-tree-inorder-traversal/description/?envType=study-plan-v2&envId=top-100-liked

力扣94-JS二叉树的中序遍历

/** 
* 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 ret = []
    function dfs(root) {
        if(root === null) {
            return root
        }
        dfs(root.left)
        ret.push(root.val)
        dfs(root.right)
    }
    dfs(root)
    return ret
};

var inorderTraversal = function (root) {
    let res = []
    if (!root) return res
    let stack = []
    while (stack.length || root) {
        while (root) {
            stack.push(root)
            root = root.left
        }
        root = stack.pop()
        res.push(root.val)
        root = root.right
    }
    return res
};
/** 
* 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) {
    const res = []
    const rec = (root) => {
        if(!root) return
        rec(root.left)
        res.push(root.val)
        rec(root.right)
    }
    rec(root)
    return res
};

 

原创文章,作者:czhdawn,如若转载,请注明出处:https://www.czhdawn.cn/archives/4922

(0)
czhdawn的头像czhdawn
上一篇 2天前
下一篇 4小时前

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注