【剑指Offer】面试题54:二叉搜索树的第k大节点

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 面试题54:二叉搜索树的第K大节点
 * 题目:给定一棵二叉搜索树,请找出其中第k大的节点。
 * @author
 * @create 2021-05-06 18:32
 */
public class Solution54 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(8);
        TreeNode node1 = new TreeNode(6);
        TreeNode node2 = new TreeNode(10);
        TreeNode node3 = new TreeNode(5);
        TreeNode node4 = new TreeNode(7);
        TreeNode node5 = new TreeNode(9);
        TreeNode node6 = new TreeNode(11);

        root.left = node1;
        root.right = node2;
        node1.left = node3;
        node1.right = node4;
        node2.left = node5;
        node2.right = node6;

        TreeNode node = KthNodeTwo(root, 1);
        System.out.println(node.val);
    }

    /**
     * 复习中序遍历,递归实现一
     * @param root
     * @return
     */
    public static TreeNode KthNode(TreeNode root, int k){
        if (root == null){
            return null;
        }
        inOrder(root);
        //因为从1开始,所以小于等于0
        if (k <= 0 || k > list.size()){
            return null;
        }
        return list.get(k-1);
    }

    static List<TreeNode> list = new ArrayList<>();
    public static List<TreeNode> inOrder(TreeNode root){
        if (root == null){
            return null;
        }
        inOrder(root.left);
        list.add(root);
        inOrder(root.right);
        return list;
    }


    /**
     * 写法二,不用全部遍历完再找,计数
     * @param root
     * @param k
     * @return
     */
    public static TreeNode KthNodeTwo(TreeNode root, int k){
        if (root == null || k <= 0){
            return null;
        }
        k1 = k;
        KthNodeCore(root);
        return target;
    }

    static TreeNode target = null;
    static int k1 = 0;
    public static void KthNodeCore(TreeNode root){
        if (root == null || k1 <= 0){
            return;
        }
        KthNodeCore(root.left);
        k1--;
        if (k1 == 0){
            target = root;
            return;
        }
        KthNodeCore(root.right);
    }


    /**
     * 方法二,中序遍历:非递归实现
     * @param root
     * @param k
     * @return
     */
    public static TreeNode KthNodeThree(TreeNode root, int k){
        if (root == null || k <= 0){
            return null;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()){
            while (cur != null){
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            k--;
            if (k == 0){
                return cur;
            }
            cur =cur.right;
        }
        return null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值