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

给定一棵二叉搜索树,请找出其中的第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);

}

 

posted @ 2020-04-07 09:19  mle123  阅读(278)  评论(0编辑  收藏  举报