【问题标题】:using javascript to code the preorder traversal使用 javascript 编写预序遍历代码
【发布时间】:2016-08-09 17:15:13
【问题描述】:
var preorderTraversal = function(root) {
    var array = [];
    if(!(root == null)){
       array.push(root.val) ;
        preorderTraversal(root.left);
        preorderTraversal(root.right);
    }
    return array;
};

测试用例为[1,2]时代码测试失败,我只输出[1],如何解决?

【问题讨论】:

    标签: javascript algorithm preorder


    【解决方案1】:

    问题是您在每个递归调用中创建了一个新的、单独的数组(然后丢弃它,因为您对递归调用返回的内容不做任何事情)。

    另一种方法是传入“累加器”数组 acc,并将其传递给每个递归调用,以便将所有元素添加到单个数组中:

    var preorderTraversal = function(root, acc = []) {
       if(!!root){
          acc.push(root.val);
          if (root.left) preorderTraversal(root.left, acc);
          if (root.right) preorderTraversal(root.right, acc);
       }
       return acc;
    };
    

    您可能还对以迭代方式而不是递归方式遍历 pre-ordered BST 感兴趣:

    var preorderTraversal = function(root) {
       /**
        * Algorithm:
        * 1. Create an empty stack [];
        * 2. Do while stack is not empty:
        * 2.1. Pop an item from stack and add it to the 'result' array.
        * 2.2. Push 'right child' of popped item to stack.
        * 2.3. Push 'left child' of popped item to stack.
       */
       if (root == null) {
         return [];
       }
    
       const stack = [];
       const result = [];
    
       stack.push(root);
    
       while(stack.length > 0) {
         let current = stack.pop();
         result.push(current.val);
    
         if (current.right) stack.push(current.right);
         if (current.left) stack.push(current.left);
       }
    
       return result;
    };
    

    【讨论】:

      【解决方案2】:

      array 是一个局部变量然后:

      1. 你用 push 把 1 放在数组上
      2. 当你再次创建array = []时递归地转到其他方面
      3. 推2
      4. 当你返回到递归堆栈数组的顶部时,仍然只有 1 个

      如果你可以发送数组作为参数可能会更好,并使用返回的数组来修改本地的

      【讨论】:

        【解决方案3】:

        您将需要一个用于 js 内联打印的辅助函数;这个辅助函数应该调用你实际的 preorder 函数。

        在您的preorder 函数中,您需要始终更新字符串“passed”(我稍后会解释“”)。如果当前节点为空,则应返回当前的字符串,否则会将其擦除。

        function doPreOrder(root, str) {
          if(!root) {
            return str;
          }
          if(!str) {
            str = "";
          }
          if(root) {
            str += root.val + ' ';
            str = doPreOrder(root.left, str);
            str = doPreOrder(root.right, str);
          }
          return str;
        }
        
        function preOrder(root) {
          var x = doPreOrder(root);
          console.log(x);
        }

        如您所见,我们首先需要使用该函数,并且只传递root。我们将一个未定义的变量传递给它,这将是我们唯一一次输入str = "" 代码,然后从那时起,str 将为每个新数据更新。最后,您只需控制台记录该变量。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-05-05
          • 2016-02-10
          • 1970-01-01
          • 2017-05-21
          • 1970-01-01
          • 2014-06-10
          • 1970-01-01
          相关资源
          最近更新 更多