剑指Offer51-二叉搜索树的第k个结点

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

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
 
    public TreeNode(int val) {
        this.val = val;
 
    }
 
}
*/
public class Solution {
    int index;//全局变量 默认为0
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot!=null){
             if(pRoot==null)
                return null;
            TreeNode node=KthNode(pRoot.left,k);
            if(node!=null)
                return node;
            if(++index==k)
                return pRoot;
            TreeNode node2=KthNode(pRoot.right,k);
            if(node2!=null)
                return node2;
        }
        return null;
    }
}
/*
TreeNode node = KthNode(root.left,k);这个node是接收左子树返回的值的,如果node不为null,
就说明已经在左子树中找到了这个值,就返回node,递归结束。如果左子树为null,就继续添加数,判断。
比如说 5 / \ 3 7 /\ /\ 2 4 6 8,递归最下面的一层为KthNode(3,1),{node=kthNode(3.left,1),
index++,node=kthNode(3.right,1)}==》(null,加入3,null)==》加入3时index++,所以index==k,
于是返回node=3给KthNode(3,1),然后KthNode(3,1)判断出它的子过程返回了一个值,说明已经找到一个数了,
于是将这个返回,如果子过程没有返回node就说明左子树中没有找到,然后index++,又判断是否等于k,
若不等于,然后KthNode(6,1),判断这个子过程有没有返回node,依次往上递归
*/

第二种方法:
本质还是中序遍历,只不过这个方法是把中序遍历的结果存储起来,然后再返回需要的结点。

import java.util.ArrayList;
public class Solution {
    ArrayList<TreeNode> list=new ArrayList<>();
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        inorder(pRoot);//中序遍历获得一个从小到大有序的序列  并且添加到list里面
        if(pRoot==null||k==0||k>list.size())//定义几种为空的情况
            return null;
        return list.get(k-1);//返回序列中第k个结点(不是值)
    }
     
    void inorder(TreeNode root){//二叉搜索树的中序遍历
        if(root==null)
            return ;
        inorder(root.left);
        list.add(root);
        inorder(root.right);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Luke@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值