题解 | #二叉搜索树的第k个节点#
二叉搜索树的第k个节点
http://www.nowcoder.com/practice/57aa0bab91884a10b5136ca2c087f8ff
import java.util.*;
import java.util.ArrayList;
import java.util.Stack;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param proot TreeNode类
* @param k int整型
* @return int整型
*/
//左根右:递增数列
public int KthNode ( TreeNode proot, int k) {
// write code here
ArrayList<Integer> ans = new ArrayList<Integer>();
Stack<TreeNode>st = new Stack<TreeNode>();
if(proot!=null) st.push(proot);
TreeNode t;
int cnt = 0;
while(!st.empty()){
t = st.pop();
ans.add(t.val);
if(t.right!=null) st.push(t.right);
if(t.left!=null) st.push(t.left);
cnt++;
}
Collections.sort(ans);
if(k<=cnt && k>0) return ans.get(k-1);
return -1;
}
}
思路:遍历后排序
也可以直接中序遍历一次 直接就是排好序的了