题解 | #二叉搜索树的第k个节点#
二叉搜索树的第k个节点
http://www.nowcoder.com/practice/57aa0bab91884a10b5136ca2c087f8ff
看到没人写题解,小透明写一下吧。用的是中序遍历,做法不怎么优美,但也算解出来了。 public class Solution {
int x;
TreeNode res = null;
public TreeNode KthNode (TreeNode proot, int k) {
// write code here
x=k;
show(proot);
if(res!=null){
res.left=null;
res.right=null;
}
return res;
}
public void show(TreeNode root){
if(x<0) return;
if(root==null){
return;
}
show(root.left);
x--;
if(x==0){
res=root;
}
show(root.right);
}
}