剑指offer JavaScript版 (62)

二叉搜索树的第K大的节点

题目描述

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

  • 根据中序遍历的结果可以找到第K大的数,在边遍历的过程中边找,需要内外通信一个计数变量。
  • 中序遍历就是先左再中最后右,所以递归是先遍历左节点,当k–为1时,则找到第K大的数,需要将标志位置为该节点,若没有,则继续按照中序遍历顺序寻找。
function KthNode(pRoot, k)
{
    // write code here
    if(pRoot==null||k<1){
        return null;
    }
    function KthNodeFind(pRoot){
        let target=null;
        if(pRoot.left!=null){
            target=KthNodeFind(pRoot.left,k);
        }
        if(target==null){
            if(k==1){
                target=pRoot;
            }
            k--;
        }
        if(target==null&&pRoot.right!=null){
            target=KthNodeFind(pRoot.right,k);
        }
        return target
    }
    return KthNodeFind(pRoot);
}
发布了93 篇原创文章 · 获赞 3 · 访问量 2477

猜你喜欢

转载自blog.csdn.net/Damp_XUN/article/details/99660774