1、题目描述:给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
2、思路:二叉搜索树中序遍历的结果就是数值按照递增进行排序。因此只需要对二叉搜索树进行中序遍历,然后取出第k-1个数即可。
3、代码:
import java.util.ArrayList; import java.util.List; /* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { List<TreeNode> resultList=new ArrayList<>(); TreeNode KthNode(TreeNode pRoot, int k) { if(pRoot==null){ return null; } interTransform(pRoot); if(k<=resultList.size() && k>=1){ return resultList.get(k - 1); } return null; } public void interTransform(TreeNode pRoot){ //左根右 if(pRoot.left!=null){ interTransform(pRoot.left); } resultList.add(pRoot); if(pRoot.right!=null){ interTransform(pRoot.right); } } }