【问题标题】:JS Depth First Traversal Pre-OrderJS深度优先遍历预购
【发布时间】:2019-09-03 19:02:35
【问题描述】:

作为一个练习,我正在编写 JavaScript 以在二叉搜索树上执行 pre-orderDepth First Traversal

注意:这是迭代,不是递归。我可以递归地做,但是 Python 中有一些方法可以迭代地做,所以我想看看这在 JS 中是如何工作的。

我的代码如下:

var preorderTraversal = function(root) {
    if(!root) return [];
    let stack = [root];
    let output = [];

    while(stack.length) {
        root = stack.shift();
        if(root !== null) {
            output.push(root.val);
            if(root.left !== null) stack.push(root.left);
            if(root.right !== null) stack.push(root.right); //Source of the issue
        }
    }

    return output;
};

假设输入是[1,2,3] 这很好用。但是,当一个输入更加多样化时,会出现一个问题,比如[1,4,3,2],它会返回:

[1,4,3,2]

而不是

[1,4,2,3]

因为当引擎碰到上面块中标记的代码行时,它会遍历右边:

     1
    / \
   4   3
  /
 2

因此,您必须以某种方式通知算法继续迭代每个左边,直到没有更多左边,然后迭代右边。递归,这很简单。

但是使用迭代,没那么多。

让我感到奇怪的是,一个类似的 Python 函数可以正常运行:

class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if root is None:
            return []

        stack, output = [root, ], []

        while stack:
            root = stack.pop()
            if root is not None:
                output.append(root.val)
                if root.right is not None:
                    stack.append(root.right)
                if root.left is not None:
                    stack.append(root.left)

        return output

很明显,导致问题的语言存在差异,或者我在算法的某个地方犯了错误。

有人知道有什么区别吗?我更感兴趣的是了解为什么,而不仅仅是让它发挥作用的捷径。

【问题讨论】:

  • 立即引起轰动的是 js 中的 shift 与 python 中的 pop
  • 宾果游戏,我认为 pop() 相当于 JS 中的 shift 但当然不是,因为 JS 有一个 pop() 方法。现在我们必须颠倒代码检查左右的顺序,它会正确地遍历它们。

标签: javascript python algorithm depth-first-search


【解决方案1】:

感谢 cmets 的帮助,这实际上是 popshift 方法的简单误用。

Python 使用 pop 而我在 JS 中使用 shift。但这意味着我们必须颠倒我们找到正确值和左值的方向。

所以JS代码实际上是:

var preorderTraversal = function(root) {
    if(!root) return [];
    let stack = [root];
    let output = [];

    while(stack.length) {
        root = stack.pop();
        if(root !== null) {
            output.push(root.val);
            if(root.right !== null) stack.push(root.right);
            if(root.left !== null) stack.push(root.left);
        }
    }   

    return output;
}

【讨论】:

    猜你喜欢
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多