題目:
給定一棵二叉搜索樹,請找出其中的第k小的結點。例如, (5,3,7,2,4,6,8) 中,按結點數值大小順序第三小結點的值爲4。
知識點:
二叉搜索樹:左節點值<根節點值<右節點值
思路:
前序遍歷,根據結點值的從小到大,將結點傳入ArrayList<TreeNode>中,在ArrayList<TreeNode>中尋找第k個(下標是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)
{
if(pRoot == null || k==0){return null;}
ArrayList<TreeNode> al = new ArrayList<>();
al = pre(pRoot,al);
if(k>al.size()){return null;}
return al.get(k-1);
}
public ArrayList<TreeNode> pre(TreeNode pRoot,ArrayList<TreeNode> al){
if(pRoot==null){return al;}
pre(pRoot.left,al);
if(pRoot!=null){al.add(pRoot);}
pre(pRoot.right,al);
return al;
}
}