LeetCode94. 二叉树的中序遍历(JavaScript解析)

题目链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal/

同样有递归法与非递归法

递归法:

/**
 * 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 arr = [];
    inorder(root,arr);
    return arr;
};

function inorder(root,res){
    if(root== null) return;
    inorder(root.left,res);
    res.push(root.val);
    inorder(root.right,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) {
    let ans = [];
    let stack = [];
    while(root !==null || stack.length !== 0){
        while(root !== null){
            stack.push(root);
            root = root.left;  //遍历完毕左子树
        }
        if(stack.length !== 0){
            root = stack.pop();
            ans.push(root.val); 
            root = root.right;  //去往右子树
        }
    }
    return ans;
};


版权声明:本文为LiLi_code原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。