前言:
剑指offer中树的题型,最后一道,下面我会刷字符串、数组相关的题。
题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
题目解析
这道题,我们首先就要抓住这个二叉搜索的特点,因为这是二叉搜索树,它的中序遍历就是从小到大的顺序进行排列的,所以我们可以先进行中序遍历,然后根据遍历结果找到第k个点就可以了。
代码样例
package com.asong.leetcode.TreeKthNode;
import java.util.ArrayList;
/**
* 二叉搜索树的第K个节点
*/
public class Solution {
public ArrayList<TreeNode> list = new ArrayList<TreeNode>();
TreeNode KthNode(TreeNode pRoot, int k)
{
Middle(pRoot);
if(list.size()>=k&&k>=1)
{
return list.get(k-1);
}
return null;
}
public void Middle(TreeNode pRoot)
{
if(pRoot!=null)
{
Middle(pRoot.left);
list.add(pRoot);
Middle(pRoot.right);
}
}
}