剑指offer-二叉搜索树的第k个结点

题目描述

给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。
 
中序遍历二叉搜索树,找到第k个结点,除了使用递归,还可以使用栈实现非递归写法
 1 public class Solution {//树 my
 2     int index = 0;
 3     TreeNode KthNode(TreeNode pRoot, int k)
 4     {
 5         if(pRoot==null){
 6             return null;
 7         }
 8         return getK(pRoot,k);
 9     }
10     TreeNode getK(TreeNode root,int k){
11         if(root==null){
12             return null;
13         }
14         TreeNode left = getK(root.left,k);
15         if(left!=null){
16             return left;
17         }
18         index++;
19         if(index==k){
20             return root;
21         }
22         TreeNode right = getK(root.right,k);
23         if(right!=null){
24             return right;
25         }
26         return null;
27     }
28 }

代码可简化为

 1 public class Solution {
 2     int index = 0;
 3     TreeNode KthNode(TreeNode pRoot, int k)
 4     {
 5         if(pRoot!=null){
 6             TreeNode left = KthNode(pRoot.left,k);
 7             if(left!=null){
 8                 return left;
 9             }
10             index++;
11             if(index==k){
12                 return pRoot;
13             }
14             TreeNode right = KthNode(pRoot.right,k);
15             if(right!=null){
16                 return right;
17             }
18         }
19         return null;
20     }
21 }