1.普通二叉树
treenode
package math;
public class TreeNode {
private int data ;
private TreeNode lchild ;
private TreeNode rchild ;
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public TreeNode getLchild() {
return lchild;
}
public void setLchild(TreeNode lchild) {
this.lchild = lchild;
}
public TreeNode getRchild() {
return rchild;
}
public void setRchild(TreeNode rchild) {
this.rchild = rchild;
}
public TreeNode(int data, TreeNode lchild, TreeNode rchild) {
super();
this.data = data;
this.lchild = lchild;
this.rchild = rchild;
}
//给出节点查找,输入数据值,返回输入值得节点
public TreeNode search(int i){
TreeNode Target = null ;
if(this.data==i){
return this ;
}else{
if(lchild!=null){
Target = lchild.search(i);
}
if(Target!=null){
return Target ;
}
if(rchild!=null){
Target = rchild.search(i);
}
}
return Target ;
}
}
binarytree
package math;
public class BinaryTree {
private TreeNode root ;
public TreeNode getRoot() {
return root;
}
public void setRoot(TreeNode root) {
this.root = root;
}
public BinaryTree(TreeNode root) {
super();
this.root = root;
}
//前序遍历
public void proper(TreeNode root){
if(root!=null){
System.out.println(root.getData());
proper(root.getLchild());
proper(root.getRchild());
}
}
}
2.顺序二叉树
把数组看做二叉树遍历
package math;
public class ArrayBinaryTree {
private int[] arr ;
public ArrayBinaryTree(int[] arr) {
super();
this.arr = arr;
}
//顺序二叉树,把数组作为一个二叉树看
public void frontshow(int index){
if(arr==null||arr.length==0){
return;
}
System.out.println(arr[index]);
if((2*index+1)<arr.length){
frontshow(2*index+1);
}
if((2*index+2)<arr.length){
frontshow(2*index+2);
}
}
}