Cosen95 / js_algorithm

🏂js数据结构与算法 系统学习
36 stars 10 forks source link

二叉树的中序遍历 #25

Open Cosen95 opened 4 years ago

Cosen95 commented 4 years ago

leetcode: https://leetcode-cn.com/problems/binary-tree-inorder-traversal/

Cosen95 commented 4 years ago

递归

第一种,我们可以通过递归来实现。这种方法代码比较简洁,语意性也比较强:

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var inorderTraversal = function(root) {
    if (root) {
        return [...inorderTraversal(root.left), root.val, ...inorderTraversal(root.right)]
    } else {
        return []
    }
};

颜色标记法

第二种是通过使用颜色标记法实现, 思路如下:

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var inorderTraversal = function(root) {
    let res = [];
    if (!root) return res
    let stack = [];
    stack.push({
        color: 'white',
        node: root
    })
    while (stack.length) {
        const { color, node } = stack.pop();
        if (color === 'grey') {
            res.push(node.val)
        } else {
            node.right && stack.push({ color: 'white', node: node.right })
            stack.push({ color: 'grey', node })
            node.left && stack.push({ color: 'white', node: node.left})
        }
    }
    return res
};