二叉搜索树的第k个结点

给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。

if(pRoot == null) return null;
        //由于是搜索二叉树,取出所有值
        ArrayList<TreeNode> allList = new ArrayList<TreeNode>();
        ArrayList<TreeNode> layerList = new ArrayList<TreeNode>();
        layerList.add(pRoot);
        while(layerList.size() != 0){
            ArrayList<TreeNode> tempList = new ArrayList<TreeNode>();
            for(TreeNode treeNode : layerList){
                allList.add(treeNode);
                if(treeNode.left != null) tempList.add(treeNode.left);
                if(treeNode.right != null) tempList.add(treeNode.right);
            }
            layerList = tempList;
        }
        if(k > allList.size() || k <= 0) return null;
        //取值排序
        for(int i = 0;i < allList.size() - 1;i ++){
            for(int j = 0;j < allList.size() - i - 1;j ++){
                if(allList.get(j).val > allList.get(j + 1).val){
                    TreeNode tempNode = allList.get(j);
                    allList.set(j, allList.get(j + 1));
                    allList.set(j + 1, tempNode);
                }
            }
        }
        //list已经排序结束
        //打印
        for(TreeNode treeNode : allList){
            System.out.println(treeNode.val);
        }
        return allList.get(k - 1);

你可能感兴趣的:(二叉搜索树的第k个结点)