面试题五十四:二叉搜索树的第K大节点

 

方法:搜索二叉树的特点就是左树小于节点,节点小于右树,所以采用中序遍历法就可以得到排序序列

BinaryTreeNode KthNode(BinaryTreeNode pNode ,int k){
            if( pNode ==null||k==0)
            return null;
           return KthNodeCore(pNode ,k );
    }
BinaryTreeNode  KthNodeCore(BinaryTreeNode pNode ,int k ){
                BinaryTreeNode target=null;
                //遍历到最小值开始递归
                if( pNode.L!=null)
                     target=KthNodeCore(pNode.L ,k );
                //k作为条件  
                if(target==null ){
                    if(k==1)
                        target=pNpde;
                     k--;
                }
                if( target==null && pNode.R==null)
                        target=KthNodeCore(pNode.R ,k );
                return target;
}

 

posted @ 2020-03-29 16:51  浪波激泥  阅读(200)  评论(0编辑  收藏  举报