剑指offer之二叉搜索树的第K个结点(Java实现)

二叉搜索树的第K个结点

NowCoder

题目描述:

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

解题思路:

思路:二叉搜索树按照中序遍历的顺序打印出来正好就是排序好的顺序。所以,按照中序遍历顺序找到第k个结点就是结果。

public  class  Solution{
     int index = 0;
     TreeNode KthNode(TreeNode ppRootOfTree, int k){ 
         if (ppRootOfTree != null){
            TreeNode treeNode = KthNode(ppRootOfTree.left,k);
            if (treeNode != null )  return treeNode;
            index ++;
            if (index == k) return ppRootOfTree;
            treeNode  = KthNode(ppRootOfTree.right,k);
            if (treeNode != null)   return treeNode;
         }
         return null;
     }
}

你可能感兴趣的:(剑指offer)