给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
解析:
二叉搜索树的定义:左节点小于根节点,根节点小于右节点;则其中序遍历即为有序排列
代码:
/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null;
public TreeNode(int val) { this.val = val;
}
} */ import java.util.*;
public class Solution { LinkedList<TreeNode> list = new LinkedList<>(); TreeNode KthNode(TreeNode pRoot, int k) { //二叉搜索树:左节点小于根节点----根节点小于右节点 //中序遍历就是排好顺序 if(k == 0 || pRoot == null){ return null; } list = newList(pRoot); if(k > list.size()){ return null; } return list.get(k - 1); } private LinkedList<TreeNode> newList(TreeNode root){ if(root != null){ newList(root.left); list.add(root); newList(root.right); } return list; } }
