剑指offer(62)二叉搜索树的第K个节点

题目描述

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

题目分析

首先,我们可以先画图。画完图后我们要想办法从中找出第K小的节点。

因为这是二叉搜索树,我们可以轻易发现它的中序遍历序列就是从小到大排列,也就是我们可以直接中序遍历,同时计数,就可以得到我们想要的节点了。

不过需要注意的是我们的计数变量k应该在函数外面,不然递归进去后回来时是无法获得已经改变了的k值的。

代码

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);
}