题解 | #二叉搜索树第k小节点#

二叉搜索树的第k个结点

http://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a

根据二叉搜索的性质可知,中序遍历即位从小到大顺序,可以使用中序遍历将其存起来取出目标节点,也可直接中序遍历同时得到节点

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    int index = 0;
    TreeNode res = null;
    TreeNode KthNode(TreeNode pRoot, int k) {
        if(pRoot==null||k == 0){
        return null;
        }
        KthNode(pRoot.left,k);
        index++;
        if(index == k){
        res = pRoot;
        }
        KthNode(pRoot.right,k);
        return res;
    }
}
全部评论

相关推荐

牛客316659795号:不是,证明hr初筛已经过了,要投给部门筛一遍
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务