剑指offer -- 二叉搜索树的第K小的结点

二叉搜索树的第k个结点

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

解法

二叉搜索树 的特点是比根节点小的永远在左边,大的永远在右边 (可以看我注释里面话的样例的图) 所以我们可以直接用中序遍历(左根右)得到一个排好序的TreeNode的List。然后直接get(k-1) 就好了(因为list小标从0开始)

/*
 运行时间:17ms 占用内存:9832KB
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

    }
    5
  3   7
 2 4 6  8
}
*/
import java.util.*;
public class Solution {
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if (pRoot == null || k == 0 ){
            return null;
        }
        List<TreeNode> list = new ArrayList<>();
        getSortTree(list,pRoot);
        if(list.size()<k){
            return null;
        }
        return list.get(k-1);
    }
    public static void getSortTree(List list , TreeNode root){
        if(root == null){
            return ;
        }
        getSortTree(list,root.left);
        list.add(root);
        getSortTree(list,root.right);
    }


}
全部评论

相关推荐

2025-11-08 21:07
门头沟学院 Java
点赞 评论 收藏
分享
2025-12-27 22:21
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务