二叉排序树查找指定区间的值

给定两个值 k1 和 k2(k1 < k2)和一个二叉查找树的根节点。找到树中所有值在 k1 到 k2 范围内的节点。即打印所有x (k1 <= x <= k2) 其中 x 是二叉查找树的中的节点值。返回所有升序的节点值。
样例
如果有 k1 = 10 和 k2 = 22, 你的程序应该返回 [12, 20, 22].


    20
   /  \
  8   22
 / \

4   12

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;

/**
 * 给定两个值 k1 和 k2(k1 < k2)和一个二叉查找树的根节点。找到树中所有值在 k1 到 k2 范围内的节点。即打印所有x (k1 <= x <= k2) 其中 x 是二叉查找树的中的节点值。返回所有升序的节点值。

您在真实的面试中是否遇到过这个题? Yes
样例
如果有 k1 = 10 和 k2 = 22, 你的程序应该返回 [12, 20, 22].

    20
   /  \
  8   22
 / \
4   12
 * 
 * @author Dell
 *
 */
public class Test11 {
     
	public static ArrayList<Integer> searchRange(TreeNode root, int k1,int k2)
	{
		if(root==null)
		{
			return null;
		}
		ArrayList<Integer> list=new ArrayList<>();
		Stack<TreeNode> s=new Stack<>();
		TreeNode p=root;
		while(p!=null||s.isEmpty()!=true)
		{
			if(p!=null)
			{
				s.push(p);
				p=p.left;
			}
			else
			{
				TreeNode temp=s.pop();
				if(temp.val>=k1&&temp.val<=k2)
					list.add(temp.val);
				p=temp.right;
			}
		}
		return list;
	}
	
	public static TreeNode insert(TreeNode t, int target)
	{
		  if(t==null)
		  {
			  t=new TreeNode(target);
			  return t;
		  }
		  else
		  {
			  if(t.val>target)
			  {
				  t.left=insert(t.left,target);
				  return t;
			  }
			  else if(t.val<target)
			  {
				  t.right=insert(t.right,target);
				  return t;  	  
			  }
				return t;	  
		  }
	
	}
	public static void midorder(TreeNode t)
	{
		if(t!=null)
		{
			midorder(t.left);
			System.out.print(t.val+" ");
			midorder(t.right);
		}
	}
	public static void main(String[] args) {
		
		Scanner sc=new Scanner(System.in);
		ArrayList<Integer> list=new ArrayList<>();
		int n=sc.nextInt();
		int[] a=new int[n];
		for(int i=0;i<a.length;i++)
		{
			a[i]=sc.nextInt();
		}
		TreeNode t=null;
		for(int i=0;i<a.length;i++)
		{
			t=insert(t,a[i]);
		}
		//midorder(t);
		int k1=sc.nextInt();
		int k2=sc.nextInt();
		list=searchRange(t,k1,k2);
       System.out.println(list);
	}

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值