package com.dl.tree;
import java.util.ArrayList;
public class TreeNode {
private int data;
private TreeNode left;
private TreeNode right;
public TreeNode(int data)
{
this.data=data;
left=null;
right=null;
}
public TreeNode()
{
super();
{
if(data>root.data)
{
if(root.right==null)
{
root.right=new TreeNode(data);
}
else{
this.insert(root.right, data);
}
} else
{
if(root.left==null)
{
root.left=new TreeNode(data);
}
else{
this.insert(root.left, data);
}
}
}
//层次遍历,利用ArrayList的可扩展性
public void leverOrder()
{
ArrayList<TreeNode> list=new ArrayList<TreeNode>();
int cur=0;
int last=0;
if(this==null)
{
System.out.println("树为空!");
}
else
{ list.add(this);
while
(cur<list.size())
{ last=list.size();
while(cur<last)
{ System.out.println(list.get(cur)+" ");
if(list.get(cur).left!=null)
{
list.add(list.get(cur).left);
}
if(list.get(cur).right!=null)
{
list.add(list.get(cur).right);
}
cur++;
}
}
}
public String toString() {
return "TreeNode [data=" + data + "]";
}
import java.util.ArrayList;
public class TreeNode {
private int data;
private TreeNode left;
private TreeNode right;
public TreeNode(int data)
{
this.data=data;
left=null;
right=null;
}
public TreeNode()
{
super();
}
//构建树
public void insert(TreeNode root,int data){
if(data>root.data)
{
if(root.right==null)
{
root.right=new TreeNode(data);
}
else{
this.insert(root.right, data);
}
} else
{
if(root.left==null)
{
root.left=new TreeNode(data);
}
else{
this.insert(root.left, data);
}
}
}
//层次遍历,利用ArrayList的可扩展性
public void leverOrder()
{
ArrayList<TreeNode> list=new ArrayList<TreeNode>();
int cur=0;
int last=0;
if(this==null)
{
System.out.println("树为空!");
}
else
{ list.add(this);
while
(cur<list.size())
{ last=list.size();
while(cur<last)
{ System.out.println(list.get(cur)+" ");
if(list.get(cur).left!=null)
{
list.add(list.get(cur).left);
}
if(list.get(cur).right!=null)
{
list.add(list.get(cur).right);
}
cur++;
}
}
}
}
//重写toString方法,打印结点值
@Overridepublic String toString() {
return "TreeNode [data=" + data + "]";
}
}
package com.dl.tree;
//测试方法
public class TreeNodeTest {
public static void main(String[] args) {
TreeNode tree=new TreeNode(6);
// tree.insert(tree, 7);
// tree.insert(tree, 2);
// tree.insert(tree, 5);
// tree.insert(tree, 53);
// tree.insert(tree, 23);
// tree.insert(tree, 21);
// tree.insert(tree, 9);
// tree.insert(tree, 65);
// tree.insert(tree, 45);
// tree.insert(tree, 34);
System.out.println(tree);
tree.leverOrder(tree);
}
}