【剑指offer】二叉搜索树的第k个结点
二叉搜索树的第k个结点
http://www.nowcoder.com/questionTerminal/ef068f602dde4d28aab2b210e859150a
题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
1、思路分析
二叉搜索树的中序遍历就是结点值的递增排列,因此只需找到中序遍历的第k个结点而已。采用递归的办法,碰到空结点返回,否则一直向左搜索,同时记录已经遍历的结点个数,如果等于k,返回当前结点,否则继续向右遍历。
2、代码
public class Solution { int count = 0; // 利用二叉树的特点,需要记录已经遍历的结点个数 TreeNode result = null; void help(TreeNode root,int k) { if(root == null) { return; } help(root.left,k); if(++count == k) { result = root; return; } else { help(root.right,k); } } TreeNode KthNode(TreeNode pRoot, int k) { if(pRoot == null || k < 0) { return null; } help(pRoot,k); return result; } }