ChuChencheng / note

菜鸡零碎知识笔记
Creative Commons Zero v1.0 Universal
3 stars 0 forks source link

二叉树的前序遍历 #2

Open ChuChencheng opened 4 years ago

ChuChencheng commented 4 years ago

问题

LeetCode 144

递归

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

    const traverse = (node) => {
        if (!node) return
        result.push(node.val)
        if (node.left) traverse(node.left)
        if (node.right) traverse(node.right)
    }

    traverse(root)

    return result
};

非递归

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var preorderTraversal = function(root) {
    const result = []
    const stack = []

    let node = root
    while (node || stack.length) {
        while (node) {
            result.push(node.val)
            stack.push(node)
            node = node.left
        }
        node = stack.pop().right
    }

    return result
};
ChuChencheng commented 4 years ago

非递归2

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var preorderTraversal = function(root) {
    const result = []
    if (!root) return result
    const stack = [root]
    while (stack.length) {
        const node = stack.pop()
        if (node.right) stack.push(node.right)
        if (node.left) stack.push(node.left)
        result.push(node.val)
    }

    return result
};