赞
踩
二叉树的定义:
一个模拟具有树形结构的集合,由多个节点连接组成一个具有层次关系的集合;
以下是二叉树的一个案例:
由这些定义与图的分析,就能有以下几个点:
class Node { public Node left;//左节点 public Node right;//右节点 public int date;//插入的值 public void addNode(Node n) { if(n.date<this.date) { if(this.left==null) this.left=n; else this.left.addNode(n);//递归,实现左,右,根节点的链接 } else{ if(right==null) { right=n; } else{ right.addNode(n); } } } public void zhongxu()//中序遍历 { if(left!=null) left.zhongxun(); System.out.print(date); if(right!=null) right.zhongxun(); } }
接下来是树的构成:
public class Mytree { private Node root;//根节点 public void add(int x)//插入数据 { Node p=new Node(); p.date=x; if(root==null) { root=p; } else { root.addNode(p); } } public void sort()//遍历 { if(root==null){ return; } else{ root.zhongxu(); } } }
主函数:
public class test_no {
public static void main(String[] args) {
Mytree tree=new Mytree();
tree.add(1);
tree.add(2);
tree.add(6);
tree.add(4);
tree.add(5);
tree.add(9);
tree.add(7);
tree.add(1);
tree.sort();
}
}
这样就简单的完成了树的节点的插入。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。