題目:二叉搜索樹的第k個結點
題目描述
給定一棵二叉搜索樹,請找出其中的第k小的結點。例如, (5,3,7,2,4,6,8) 中,按結點數值大小順序第三小結點的值爲4。
解題思路:
中序遍歷,找到第k個元素即可。
代碼實現:
/*
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 {
TreeNode KthNode(TreeNode pRoot, int k){
// 代碼的魯棒性
if (pRoot == null || k == 0) {
return null;
}
ArrayList<TreeNode> al=new ArrayList<TreeNode>();
getKthNode(al,pRoot, k);
if(al.size()<k) {
return null;
}
return al.get(k-1);
}
private void getKthNode(ArrayList<TreeNode> al, TreeNode pRoot, int k) {
if(pRoot==null) {
return;
}
getKthNode(al,pRoot.left, k);
al.add(pRoot);
if(al.size()==k) {
return ;
}
getKthNode(al,pRoot.right, k);
}
}