leetcode 589 N 叉树的前序遍历

121 阅读1分钟

解法:迭代

思路: 利用栈的思想,先讲root节点压入栈中,遍历栈的长度,如果栈不为空,将栈顶元素弹出,并将栈顶元素的值储存。然后遍历栈顶元素的子节点,并压入栈中,循环执行。最后返回储存的结果

var preorder = function(root) {
    if (!root) return []
    let stack = []
    let res = []
    stack.push(root)
    while(stack.length) {
        let node = stack.pop()
        let len = node.children.length
        res.push(node.val)
        while(len--) {
            stack.push(node.children[len])
        }
    }
    return res
};

解法二:递归

思路: 同二叉树的前序遍历法类同

var preorder = function(root) {
    let stack = []
    function deepTree (root) {
        if (!root) return
        stack.push(root.val)
        for(let i = 0; i < root.children.length; i++) {
            deepTree(root.children[i])
        }
    }
    deepTree(root)
    return stack
};