二叉树的构建
首先创建三个类
public class TreeNode {
public TreeNode leftChild;
public TreeNode rightChild;
public Integer value;
public TreeNode ( Integer value) {
this . value= value;
}
}
public class BinaryTree {
TreeNode root;
public void insert ( Integer value) {
TreeNode node= new TreeNode ( value) ;
if ( root== null ) {
root= node;
return ;
}
TreeNode parent;
TreeNode temp= root;
while ( true ) {
parent= node;
if ( node. value> temp. value) {
temp= temp. rightChild;
if ( temp== null ) {
parent. rightChild= node;
return ;
}
} else {
temp= temp. leftChild;
if ( temp== null ) {
parent. leftChild= node;
return ;
}
}
}
}
public TreeNode insertD ( Integer value, TreeNode Dnode ) {
TreeNode node= new TreeNode ( value) ;
if ( root== null ) {
root= node;
return root;
}
while ( true ) {
if ( value> Dnode . value) {
if ( Dnode . rightChild== null ) {
Dnode . rightChild= node;
return root;
}
return insertD ( value, Dnode . rightChild) ;
} else {
if ( Dnode . leftChild== null ) {
Dnode . leftChild= node;
return root;
}
return insertD ( value, Dnode . leftChild) ;
}
}
}
}
public class TestTree {
public static void main ( String [ ] args) {
BinaryTree t1= new BinaryTree ( ) ;
t1. insert ( 5 , t1. root) ;
t1. insertD ( 5 , t1. root) ;
t1. insertD ( 2 , t1. root) ;
}
}