简体   繁体   中英

Function returning undefined instead of boolean. BST, LeetCode

I am working on a problem in leetcode. the code is written in javascript.

https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/

Whenever I test the code it returns undefined, however when i put console.log(true) right before my return statement, it prints true, but still does not return true.

var findTarget = function (root, k) {
  var stack = [];
  var currentNode = root;
  var arrayofVals = [];

  var traverse = function (currentNode) {
    console.log(currentNode);
    console.log(stack);
    arrayofVals.push(currentNode.val);

    if (currentNode.right !== null) {
      stack.push(currentNode.right);
    }

    if (currentNode.left !== null) {
      currentNode = currentNode.left;
      traverse(currentNode);
    }

    if (stack.length > 0 ) {
      currentNode = stack.pop();
      traverse(currentNode);
    } else {
      console.log(arrayofVals)

      for (var i = 0; i <= arrayofVals.length; i++) {
        for (var j = 0; j <= arrayofVals.length; j++) {
          if (i === j) {
            continue;
          }
          if(arrayofVals[i] + arrayofVals[j] === k) {
            console.log(1 === 1);
            return (1 === 1);
          }
        }
      }
      return false;
    }
  }
  traverse(currentNode);   
}

Can someone help me understand why my code returns undefined? I have had this problem before, but only when returning bool.

Thanks for your help!

Right now, findTarget isn't returning anything. You'll want to do return traverse(currentNode); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM