面试题54:二叉搜索树的第k大结点

题目:

给定一棵二叉搜索树,请找出其中第k大的结点。

分析:

对二叉搜索树的中序遍历结果,是一个从小到大的有序序列,要找第K大结点,可以将有序序列变成从大到小的,也就是使用右根左的顺序递归遍历,同时使用一个计数器,当计数器达到k的时候,就是第k大结点了。

解法:

package com.wsy;

class Tree {
    private int value;
    private Tree left;
    private Tree right;

    public Tree() {
    }

    public Tree(int value) {
        this.value = value;
        this.left = this.right = null;
    }

    public Tree(int value, Tree left, Tree right) {
        this.value = value;
        this.left = left;
        this.right = right;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Tree getLeft() {
        return left;
    }

    public void setLeft(Tree left) {
        this.left = left;
    }

    public Tree getRight() {
        return right;
    }

    public void setRight(Tree right) {
        this.right = right;
    }
}

public class Main {
    public static int count;

    public static void main(String[] args) {
        Tree tree = init();
        int k = 3;
        getKth(tree, k);
    }

    public static Tree init() {
        Tree tree8 = new Tree(8);
        Tree tree6 = new Tree(6);
        Tree tree4 = new Tree(4);
        Tree tree2 = new Tree(2);
        Tree tree7 = new Tree(7, tree6, tree8);
        Tree tree3 = new Tree(3, tree2, tree4);
        Tree tree5 = new Tree(5, tree3, tree7);
        return tree5;
    }

    public static void getKth(Tree tree, int k) {
        if (tree == null || k < 1) {
            return;
        }
        if (tree.getRight() != null) {
            getKth(tree.getRight(), k);
        }
        count++;
        if (count == k) {
            System.out.println("第" + k + "大的结点是:" + tree.getValue());
        }
        if (tree.getLeft() != null) {
            getKth(tree.getLeft(), k);
        }
    }
}

 

面试题54:二叉搜索树的第k大结点面试题54:二叉搜索树的第k大结点 王劭阳 发布了181 篇原创文章 · 获赞 1 · 访问量 7421 私信 关注
上一篇:[Java]使用ArrayList类来把54张扑克牌发给3位玩家各17张,剩下3张是底牌


下一篇:54. 螺旋矩阵(java)