题目依旧来自《剑指Offer》和牛客网在线编程。
【题目】给定一颗二叉搜索树,请找出其中的第k小的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第3小结点的值为4。
/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { TreeNode KthNode(TreeNode pRoot, int k) { } }
【分析1】题目中很明确的告诉了我们这是一棵二叉搜索树,因此一旦中序遍历这棵二叉搜索树,我们将得到一个有序的序列。而在一个有序的序列中找出第K小的数只需要O(1)的时间复杂度。
【分析2】至此,我们得到了一个很直观的解法。就是中序遍历二叉树得到有序集合,然后返回集合中的第K个元素。
【代码1】
import java.util.*; /* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { TreeNode KthNode(TreeNode pRoot, int k) { ArrayList<Integer> list = new ArrayList<>(); TreeNode res = null; int val = 0; to_list(pRoot,list); if(k > 0 && k <= list.size()){ val = list.get(k-1); res = getRoot(pRoot,val); return res; } return res; } public void to_list(TreeNode pRoot,ArrayList<Integer> list){ if(pRoot != null){ to_list(pRoot.left,list); list.add(pRoot.val); to_list(pRoot.right,list); } } public TreeNode getRoot(TreeNode pRoot, int k){ if(pRoot == null) return null; if(pRoot.val == k) return pRoot; if(pRoot.val > k) return getRoot(pRoot.left, k); if(pRoot.val < k) return getRoot(pRoot.right, k); return null; } }
【分析3】上面的解法首先需要中序遍历二叉树,将二叉树这种数据结构转化成集合的结构后,再获取值,显然有些许的麻烦。既然已经是有序的二叉搜索树,能够在中序遍历的过程中直接获取值呢?答案是肯定的,只需要设置一个全局计数器即可。
【代码2】
/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { public int count = 0; TreeNode KthNode(TreeNode pRoot, int k) { if(pRoot != null){ TreeNode p = KthNode(pRoot.left,k); if(p != null) return p; if(++count == k) return pRoot; TreeNode q = KthNode(pRoot.right,k); if(q != null) return q; } return null; } }