简体   繁体   English

函数返回undefined而不是boolean。 BST,LeetCode

[英]Function returning undefined instead of boolean. BST, LeetCode

I am working on a problem in leetcode. 我正在处理leetcode中的问题。 the code is written in javascript. 该代码是用javascript编写的。

https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/ 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. 每当我测试代码时,它都会返回未定义,但是当我将console.log(true)放在我的return语句之前时,它会输出true,但仍然不会返回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. 目前, findTarget不返回任何内容。 You'll want to do return traverse(currentNode); 您将要return traverse(currentNode); .

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

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