本文共 974 字,大约阅读时间需要 3 分钟。
树
给定一棵二叉搜索树,请找出其中的第 k 小的结点。例如,(5,3,7,2,4,6,8)中,按结点数值大小顺序第三小结点的值为 4。
5 / \ 3 7 / \ / \ 2 4 6 8
对一棵二叉搜索树进行中序遍历,那么得到的遍历序列就是递增排序的。
public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}
public class Solution { private int num; private TreeNode node; TreeNode KthNode(TreeNode pRoot, int k) { // 特殊情况返回空 if (pRoot == null || k < 1) { return null; } num = k; KthNode(pRoot); return node; } /** * 对二叉搜索树进行中序遍历,并找到第 k 小结点 * @param pRoot */ void KthNode(TreeNode pRoot) { if (pRoot.left != null) { KthNode(pRoot.left); } num--; if (num == 0) { node = pRoot; return; } if (pRoot.right != null) { KthNode(pRoot.right); } }}
转载地址:http://eyjvb.baihongyu.com/