剑指offer--二叉搜索树的第k个结点(Java)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40244153/article/details/87937066

题目:
  给定一棵二叉搜索树,请找出其中的第k小的结点。
思路:
      二叉查找树的中序遍历结果是节点的从小到大排序序列  
      设置全局变量index=0,对BST进行中序遍历,每遍历一个结点,index+1,当index=k时,该结点即为所求结点。

考点:知识迁移能力

实现:

int index=0;
    TreeNode KthNode(TreeNode pRoot, int k){
        if(pRoot==null || k<=0)
            return null;
        return getKthNode(pRoot,k);
    }

    private TreeNode getKthNode(TreeNode pRoot, int k){
        TreeNode kthNode=null;
        if(pRoot.left!=null)
            kthNode=getKthNode(pRoot.left,k);
        if(kthNode==null){
            index++;
            if(k==index)
                kthNode = pRoot;
        }
        if(kthNode==null && pRoot.right!=null)
            kthNode=getKthNode(pRoot.right,k);
        return kthNode;
    }

 

收获:

       1.熟练掌握二叉搜索树和中序遍历。

  2.用中序遍历实现功能时,一定要注意返回值是否满足要求。

猜你喜欢

转载自blog.csdn.net/weixin_40244153/article/details/87937066
今日推荐