二叉搜索树的第K个结点分析

20 篇文章 0 订阅
7 篇文章 0 订阅

题目依旧来自《剑指Offer》和牛客网在线编程。

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

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

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

    }

}
*/
public class Solution {
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        
    }


}

【分析1】题目中很明确的告诉了我们这是一棵二叉搜索树,因此一旦中序遍历这棵二叉搜索树,我们将得到一个有序的序列。而在一个有序的序列中找出第K小的数只需要O(1)的时间复杂度。

【分析2】至此,我们得到了一个很直观的解法。就是中序遍历二叉树得到有序集合,然后返回集合中的第K个元素。

【代码1】

import java.util.*;
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

    }

}
*/
public class Solution {
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        ArrayList<Integer> list = new ArrayList<>();
        TreeNode res = null;
        int val = 0;
        to_list(pRoot,list);
        if(k > 0 && k <= list.size()){
            val = list.get(k-1);
            res = getRoot(pRoot,val);
            return res;
            
        }
        
        return res;
        
    }

    public void to_list(TreeNode pRoot,ArrayList<Integer> list){
        if(pRoot != null){
            to_list(pRoot.left,list);
            list.add(pRoot.val);
            to_list(pRoot.right,list);
        }
    }
    
    public TreeNode getRoot(TreeNode pRoot, int k){
        if(pRoot == null)
            return null;
        if(pRoot.val == k)
            return pRoot;
        if(pRoot.val > k)
            return getRoot(pRoot.left, k);
        if(pRoot.val < k)
            return getRoot(pRoot.right, k);
        return null;
    }

}

【分析3】上面的解法首先需要中序遍历二叉树,将二叉树这种数据结构转化成集合的结构后,再获取值,显然有些许的麻烦。既然已经是有序的二叉搜索树,能够在中序遍历的过程中直接获取值呢?答案是肯定的,只需要设置一个全局计数器即可。

【代码2】

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

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

    }

}
*/
public class Solution {
    public int count = 0;
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot != null){
            TreeNode p = KthNode(pRoot.left,k);
            if(p != null)
                return p;
            if(++count == k)
                return pRoot;
            TreeNode q = KthNode(pRoot.right,k);
            if(q != null)
                return q;
        }
        return null;
    }


}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值