该方法采用的是先前序再排列,然后打印。第二种方法是根据二叉树的特点,左子树节点的值小于根节点小于右子树节点的值。所以中序打印出来的数据就是按照顺序排列好的。以下是代码:
import java.util.*;
public class Solution {
// 前序遍历;
public int KthNode (TreeNode proot, int k) {
// write code here
// 获得list的长度
int len=0;
Listlist1=new ArrayList();
Listlist2=new ArrayList();
list1=get_list(list2,proot);
// 什么是快乐星球
for(int i=0;icount){
return -1;
}
list1.sort(null);
System.out.println(list1.size());
return list1.get(k-1);
}
// 先遍历二叉树
public List get_list(List list,TreeNode proot){
if(proot!=null){
list.add(proot.val);
if(proot.left!=null){
get_list(list,proot.left);
}
if(proot.right!=null){
get_list(list,proot.right);
}
}
return list;
}
}
第二种方法
import java.util.*;
public class Solution {
public int KthNode (TreeNode proot, int k) {
// write code here
Listlist=new ArrayList (); List list2=new ArrayList (); list=get_list(list2,proot); if(k<=0||k>list.size()){ System.out.println(123); return -1; } if(proot==null){ System.out.println(124); return -1; } return list.get(k-1); }
// 利用中序遍历
public List get_list(List list1,TreeNode root){
if (root != null) {
get_list(list1,root.left);
list1.add(root.val);
get_list(list1,root.right);
}
return list1;
}
}



