二叉排序树的构建及中序遍历,层序遍历

时间:2022-09-12 22:44:23
package demo1;

import java.util.LinkedList;

import org.junit.Test;

class Node{
    int data;
     Node rightChild;
     Node leftChild;
    public Node(int data){
        this.data=data;
    }
}
public class BinaryTree {
    
    private Node root;
    public BinaryTree(){
        root=null;
    }
    public   void insert(int num){
        Node node=new Node(num);
        if(root==null){
            root=node;
            return;
        }else{
            Node current=root;
            Node parent;
            while(true){
                parent=current;
                if(num<current.data){
                    current=parent.leftChild;
                    if(current==null){
                        parent.leftChild=node;
                        return;
                    }
                }else{
                    current=parent.rightChild;
                    if(current==null){
                        parent.rightChild=node;
                        return;
                    }
                    
                }
            }
            
        }
    }
    @Test
    public  void te() {
        int[]arr={88,55,2,6,44,1,75,3};
        for (int i : arr) {
            insert(i);
        }
        bianli(root);
        cengxu(root);
    }
    public void cengxu(Node node){
        if(node==null){
            return;
        }
        LinkedList<Node>list=new LinkedList<>();
        Node current=null;
        list.addLast(node);
        while(!list.isEmpty()){
            current=list.removeFirst();
            System.out.print(current.data+",");
            if(current.leftChild!=null){
                list.addLast(current.leftChild);
            }
            if(current.rightChild!=null){
                list.addLast(current.rightChild);
            }
        }
    }
    public void bianli(Node node){
        if(node!=null){
            bianli(node.leftChild);
            System.out.print(node.data+",");
            bianli(node.rightChild);
        }
        
    }

}