Skip to content

问题:二叉搜索树的第k个节点 #4

@qiufeihong2018

Description

@qiufeihong2018

递归算法:好像写错了,解法思路是对的,但是运行就报错,
运行环境:vscode集成leetcode插件

/*
 * @lc app=leetcode.cn id=230 lang=javascript
 *
 * [230] 二叉搜索树中第K小的元素
 */
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} k
 * @return {number}
 */
function kthSmallest(root, k) {
    const arr = [];
    loopThrough(root, arr);
    if (k > 0 && k <= arr.length) {
      return arr[k - 1];
    }
    return null;
  }

  function loopThrough(node, arr) {
    if (node) {
      loopThrough(node.left, arr);
      arr.push(node);
      loopThrough(node.right, arr);
    }
  }

✘ Wrong Answer
  ✘ 0/91 cases passed (N/A)
  ✘ testcase: '[3,1,4,null,2]\n1'
  ✘ answer: NaN
  ✘ expected_answer: 1
  ✘ stdout:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions