题解 | #二叉搜索树的第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);
}

}

全部评论
昨天刚做完今天就题改了,现在是输出是val,不是TreeNode了,不过思路还是一样的
1
送花
回复
分享
发布于 2021-11-20 14:51

相关推荐

4 收藏 评论
分享
牛客网
牛客企业服务