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

来源:互联网 发布:叙永网络歌手大赛 编辑:程序博客网 时间:2024/05/20 11:46
给定两个值 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);}}


原创粉丝点击