数据结构与算法每日一题——二叉树(94. 二叉树的中序遍历)

59 阅读1分钟

94. 二叉树的中序遍历

image.png

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



 二、非递归
 var inorderTraversal = function (root) {
   let res = [], stack = []
     while(stack.length || root) {
         if(root) {
             stack.push(root)
             root = root.left
         } else {
             const node = stack.pop()
             res.push(node.val)
             root = node.right
         }
     }
     return res
 };
//  中序遍历:左中右
//  压栈顺序:右中左
var inorderTraversal = function(root, res = []) {
    const stack = [];
    if (root) stack.push(root);
    while(stack.length) {
        const node = stack.pop();
        if(!node) {
            res.push(stack.pop().val);
            continue;
        }
        if (node.right) stack.push(node.right); // 右
        stack.push(node); // 中
        stack.push(null);
        if (node.left) stack.push(node.left); // 左
    };
    return res;
};