Java数据结构创建二叉树


Java数据结构创建二叉树

import java.util.LinkedList;

import java.util.Queue;



 class Node{

   int data;

   Node leftNode, rightNode;

   Node() {

      leftNode = null;

      rightNode = null;     

      this.data = data;

   }

   Node(int data) {

      leftNode = null;

      rightNode = null;     

      this.data = data;

   }   



   int getData() {

      return this.data;    

   }



   Node getleftNode() {

      return this.leftNode;    

   }       



   Node getRightNode() {

      return this.leftNode;    

   }



   void setData(int data) {

      this.data = data;

   }           

   void setleftNode(Node leftNode) {

      this.leftNode = leftNode;    

   }



   void setRightNode(Node rightNode) {

      this.leftNode = rightNode;          

   }

}

public class CreatingBinaryTree {

   public static void main(String[] args){

      Node node = new Node(50);

      node.leftNode = new Node(60);

      node.leftNode.leftNode = new Node(45);

      node.leftNode.rightNode = new Node(64);



      node.rightNode = new Node(60);

      node.rightNode.leftNode = new Node(45);

      node.rightNode.rightNode = new Node(64);

      System.out.println("Binary Tree Created Pre-order of its elements is: ");

      preOrder(node);      

   }



   public static void preOrder(Node root){

      if(root !=null){

         System.out.println(root.data);

         preOrder(root.leftNode);

         preOrder(root.rightNode);        

      }

   }

}