树---二叉搜索树的第K个节点

2022-10-08

给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。

分析:二叉搜索树就是每个节点x,大于其左子树的值,小于其右子树的值,其中序排序是递增的。使用中序遍历,每遍历一个节点,k-1,直到k减到1,即为第k小的节点

/* function treenode(x) {

    this.val = x;

    this.left = null;

    this.right = null;

} */

function kthnode(proot, k) {

  if (proot === null || k === 0) {

    return null;

  }

  // 为了能追踪k,应该把kthnodecore函数定义在这里面,k应该在kthnodecore函数外面

  function kthnodecore(proot) {

    let target = null;

    if (proot.left !== null) {

      target = kthnodecore(proot.left, k);

    }

    if (target === null) {

      if (k === 1) {

        target = proot;

      }

      k--;

    }

    if (target === null && proot.right !== null) {

      target = kthnodecore(proot.right, k);

    }

    return target;

  }

  return kthnodecore(proot);

}

 

《树---二叉搜索树的第K个节点.doc》

下载本文的Word格式文档,以方便收藏与打印。