1 有序数组插入到树中 2 层次遍历2叉树

本文详细介绍了如何使用队列实现二叉排序树的层次遍历过程,包括将根节点放入队列并按层次顺序输出节点值的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 用二叉排序树存储

2 层次遍历需要用队列 先把跟放到队列中,然后出队一个同时将其左右child分别入队,知道队空

 

import java.util.ArrayList;
import java.util.List;


/**
 * 1 有序数组放入到树中,二叉排序树
 * 2 层次遍历这个树
 * @author Acer
 *
 */
public class TreeLayerAccess {
 
 public static void main(String[] args) {
  /*
  int[] a = {5,3,9,1,7,2,8};
  TaNode root = null;
  for(int i =0;i<a.length;i++){
   root = add(root, a[i]);
  }
  midAccess(root);
  */
  
  TaNode root = null;
  int[] a =new int[]{1,2,3,4,5,6,7,8,9};
  root = OderArrayInsertIntoTree(root, a, 0, a.length-1);
  //midAccess(root);
  
  layerAccess(root);
 }
 
 public static void layerAccess(TaNode root){
  
  if(root == null)
   return;
  
  List<TaNode> queue = new ArrayList<TaNode>();
  System.out.println(queue.size());
  queue.add(root);
  
  while(queue.size()!=0){
   
   TaNode node = queue.remove(0);
   System.out.print(node.value+" ");
   if(node.left!=null)
    queue.add(node.left);
   if(node.right!=null)
    queue.add(node.right);
   
  }
 }
 
 /**
  * 有序数组放入到树中,二叉排序树
  * @param root
  * @param a
  * @param begin
  * @param end
  * @return
  */
 public static TaNode OderArrayInsertIntoTree(TaNode root, int[] a , int begin ,int end){
  if(begin<=end){
   int mid = (begin+end)/2;
   root= add(root, a[mid]);
   OderArrayInsertIntoTree(root, a, begin, mid-1);
   OderArrayInsertIntoTree(root, a, mid+1, end);
  }
  return root;
 }
 
 public static TaNode add(TaNode root , int value){
  
  if(root==null){
   return new TaNode(value);
  }
  else{
   if(value<root.value){
    if(null == root.left){
     root.left = new TaNode(value);
    }
    else{
     add(root.left, value);
    }
   }
   else{
    if(null == root.right){
     root.right = new TaNode(value);
    }
    else{
     add(root.right, value);
    }
   }
   return root;
  }
  
 }
 
 
 public static void midAccess(TaNode root ){
  if(root!=null){
   midAccess(root.left);
   System.out.print(root.value);
   midAccess(root.right);
  }
 }
}

class TaNode{
 
 public TaNode(int value){
  this.value = value;
 }
 
 public int value;
 
 public TaNode left;
 
 public TaNode right;
 
 
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值