简体   繁体   English

JavaScript二进制搜索树按顺序遍历返回undefined作为答案的一部分

[英]JavaScript Binary Search Tree in-order traversal returning undefined as part of answer

I'm writing a recursive in-order traversal method for a BST in JS. 我正在为JS中的BST编写递归的有序遍历方法。 The method is supposed to return numerical leaf values in order within an array. 该方法应该在数组内按顺序返回数值叶值。 So far, my written method does that. 到目前为止,我的书面方法就是如此。 But in addition to the in-order numbers, it also returns 3 'undefined' at the end of my array as well. 但是除了有序数字之外,它还会在我的数组末尾返回3'undefined'。 My code for the in order method is here: 我的in order方法的代码在这里:

this.inorder = function(){
        let travArr = [];

        function recurTrav(node){
            if(node.left == null && node.right == null){
                console.log("leaf: " + node.value);
                return node.value;
            }
            else if(node.right == null){
                console.log("right is null, val: " + node.value);
                travArr.push(recurTrav(node.left));
                travArr.push(node.value);
            }
            else if(node.left == null){
                console.log("left is null, val:" + node.value);
                travArr.push(node.value);
                travArr.push(recurTrav(node.right));
            }
            else{
                console.log("no nulls:");
                travArr.push(recurTrav(node.left));
                travArr.push(node.value);
                travArr.push(recurTrav(node.right));
            }
        }

        recurTrav(this.root);
        return travArr;
}

The this.root is the root node of the BST. this.root是BST的根节点。 I have an add method that I didn't include here, for the sake of simplicity. 为简单起见,我有一个我没有包含的添加方法。 Nodes have a value, left, and right property. 节点具有值,左和右属性。

If I added the numbers 3, 2, 5, 6, 14, 8 to my BST in that order, my .inorder() method returns [2, 3, 5, 6, 8, 14, undefined, undefined, undefined] for some reason. 如果我按顺序将.inorder()到我的BST,我的.inorder()方法将返回[2, 3, 5, 6, 8, 14, undefined, undefined, undefined] .inorder() [2, 3, 5, 6, 8, 14, undefined, undefined, undefined]某些原因。 I can't figure out where those 3 undefined's are coming from. 我无法弄清楚那3个未定义的来自哪里。 I think it might be because of my travArr.push(), which might potentially return 'undefined'. 我想这可能是因为我的travArr.push(),它可能会返回'undefined'。

I realize I could probably just do some array manipulation to take those 'undefined' out, but I really want to understand how I wrote my code wrong in the first place. 我意识到我可能只是做一些数组操作来取消那些'未定义',但我真的想要了解我的代码编写错误。 If including my full code for my BST is easier, just let me know and I'll include it. 如果我的BST包含我的完整代码更容易,请告诉我,我会将其包括在内。

You might have a look to this part: 您可以查看此部分:

function recurTrav(node) {
    if (node.left == null && node.right == null){
        console.log("leaf: " + node.value);
        return node.value;                                 // returns a value
    } else if(node.right == null){
        console.log("right is null, val: " + node.value);
        travArr.push(recurTrav(node.left));                // <------ could take undefined
        travArr.push(node.value);                          // no return until end of funct
    }
    //..
    // missing return, takes default return value.
}

Solution: Push only if necessary and call function without using the result for pushing. 解决方案:仅在必要时按下并调用功能而不使用推送结果。

function recurTrav(node) {
    if (!node.left && !node.right) {                      // falsy check incl undefined/null
        console.log("leaf: " + node.value);
        travArr.push(node.value);
        return;                                           // omit else parts
    }                                                     // with early returns
    if (!node.right) {
        console.log("right is null, val: " + node.value);
        recurTrav(node.left);
        travArr.push(node.value);
        return;
    }
    if (!node.left) {
        console.log("left is null, val:" + node.value);
        travArr.push(node.value);
        recurTrav(node.right);
        return;
    }
    console.log("no nulls:");
    recurTrav(node.left);
    travArr.push(node.value);
    recurTrav(node.right);
}

Given a simple Node constructor 给出一个简单的Node构造函数

class Node
{ constructor (value, left, right)
  { this.value = value
    this.left = left
    this.right = right
  } 
}

And a simple Tree constructor 还有一个简单的Tree构造函数

class Tree
{ constructor (root)
  { this.root = root
  }

  ...
}

We can implement Tree#inorder without the need to null-check left and right branches individually 我们可以实现Tree#inorder无需为null检查leftright分别分支

inorder ()
{ if (this.root === undefined)
    return []

  else
    return [ ...new Tree (this.root.left).inorder ()
           , this.root.value
           , ...new Tree (this.root.right).inorder ()
           ]
}

Run the complete program below to verify the results in your own browser 运行下面的完整程序,在您自己的浏览器中验证结果

 class Node { constructor (value, left, right) { this.value = value this.left = left this.right = right } } class Tree { constructor (root) { this.root = root } inorder () { if (this.root === undefined) return [] else return [ ...new Tree (this.root.left).inorder () , this.root.value , ...new Tree (this.root.right).inorder () ] } } const n = new Node ( 3 , new Node ( 2 , new Node (1) , undefined ) , new Node ( 6 , new Node ( 4 , undefined , new Node (5) ) , new Node (7) ) ) const t = new Tree (n) console.log (t.inorder ()) // [ 1, 2, 3, 4, 5, 6, 7 ] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在这个二叉搜索树 (JavaScript) 代码中,有序、前序和后序的递归是如何工作的? - How is the recursion of in-order, pre-order and post-order working in this Binary Search Tree (JavaScript) code? Javascript-按顺序遍历二叉树。 上一个值正在打印未定义 - Javascript - Binary tree traversal in order. Last value is printing undefined 在 JavaScript 中递归二叉搜索树遍历结束时返回一个值 - Returning a value at the end of a recursive binary search tree traversal in JavaScript Javascript:二叉搜索树顺序遍历递归混淆 - Javascript: Binary Search Tree in order traversal recursive confusion 二叉搜索树递归返回未定义 - Javascript - Binary Search Tree Recursion returning undefined - Javascript 如果在二叉树(不是 BST)上找到值,如何停止有序 DFS 遍历 - How to stop In-order DFS traversal if value is found on a binary tree (not BST) 使用 Javascript 的二叉树级顺序遍历 - Binary Tree Level Order Traversal using Javascript 在 Javascript 上显示二叉搜索树遍历(递归方式) - Display Binary Search Tree Traversal on Javascript (Recursive way) 尝试返回二叉树的级别顺序遍历 - Trying to return a level order traversal of a binary tree 二叉搜索树遍历 - 查找最接近的值 - Binary Search Tree traversal - Find Closest Value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM