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

一、题目描述

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

二、解题思路

   思路:搜索二叉树采用中序遍历的结果就是排好序的,我们用list保存下遍历的结果,在找到第k个值。

   改进思路:不用list保存,使用一个变量作为计数器,累加到k值时,返回(递归遍历)

三、java代码

public class Solution_63 {
     /**
      * 给定一棵二叉搜索树,请找出其中的第k小的结点。
      * 例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。
      */
	ArrayList<TreeNode> arr = new ArrayList<TreeNode>();
	TreeNode KthNode_1(TreeNode pRoot, int k)
    {
        //搜索二叉树采用中序遍历的结果就是排好序的,我们用list保存下遍历的结果,在找到第k个值。
		if(pRoot == null || k<=0){
			return null;
		}
		inOrder(pRoot);
		TreeNode treeNode = pRoot;
		if(k<=arr.size()){
			treeNode = arr.get(k-1);
		}else {
			return null;
		}
		return treeNode;
    }
	public void inOrder(TreeNode root){  //中序遍历
		if(root == null){
			return;
	     }
		if(root.left != null){
			inOrder(root.left);
		}
		arr.add(root);
		if(root.right != null){
			inOrder(root.right);
		}
	}	
	
	//改进:不用list保存,使用一个变量作为计数器,累加到k值时,返回(递归遍历)
	int index = 0;  //计数器
	TreeNode KthNode_2(TreeNode pRoot, int k){
		if(pRoot != null){
			TreeNode node = KthNode_2(pRoot.left, k);
			if(node != null){
				return node;
			}
			index ++;
			if(index == k){
				return pRoot;
			}
			node = KthNode_2(pRoot.right, k);
			if(node != null){
				return node;
			}
		}
		return null;
	} 
	
	//也是改进版,非递归遍历,用循环
	 int count = 0;    //计数器
	    TreeNode KthNode_3(TreeNode pRoot, int k)
	    {
	        if(count > k || pRoot == null)
	            return null;
	        TreeNode p = pRoot;
	        Stack<TreeNode> LDRStack = new Stack<TreeNode>();
	        TreeNode kthNode = null;
	        while(p != null || !LDRStack.isEmpty()){
	            while(p != null){
	                LDRStack.push(p);
	                p = p.left;
	            }
	            TreeNode node = LDRStack.pop();
	            System.out.print(node.val+",");
	            count++;
	            if(count == k){
	                kthNode = node;
	                break;
	            }
	            p = node.right;
	        }
	        return kthNode;
	    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值