public class BinaryTree{
private TreeNode root=null;
public BinaryTree(){
root=new TreeNode(1,"A");
}
/*
构建二叉树
A
B C
D E F
*/
public void createBinaryTree(){
TreeNode nodeB=new TreeNode(2,"B");
TreeNode nodeC=new TreeNode(3,"C");
TreeNode nodeD=new TreeNode(4,"D");
TreeNode nodeE=new TreeNode(5,"E");
TreeNode nodeF=new TreeNode(6,"F");
root.leftChild=nodeB;
root.rightChild=nodeC;
nodeB.leftChild=nodeD;
nodeB.rightChild=nodeE;
nodeC.rightChild=nodeF;
}
public class TreeNode{
private int index; //索引|下标
private String data; //数据域
private TreeNode leftChild; //左孩子
private TreeNode rightChild; //右孩子
public TreeNode(int index,String data){
this.index=index;
this.data=data;
this.leftChild=null;
this.rightChild=null;
}
public void setIndex(int index){
this.index=index;
}
public int getIndex(){
return index;
}
public void setData(String data){
this.data=data;
}
public String getData(){
return data;
}
/*求二叉树的高*/
public int getHeight(){
return getHeight(root);
}
private int getHeight(TreeNode node){
if(node=null){
return 0;
}else{ //左子树和右子树中谁大返回谁
int i=getHeight(node.leftChild);
int j=getHeight(node.rightChild);
return (i>j) ? i+1:j+1;
}
}
/*获取二叉树的节点数*/
public int getSize(){
return getSize(root);
}
private int getSize(TreeNode node){
if(node==null){
return 0;
}else{
return 1+getSize(node.leftChild)+getSize(node.rightChild);
}
}
/*前序遍历*/
public void preOrder(TreeNode node){
if(node==null){
return;
}else{
System.out.println("preOrder data:"+node.getData());
preOrder(node.leftChild);
preOrder(node.rightChild);
}
}
/*中序遍历*/
public void midOrder(TreeNode node){
if(node==null){
return;
}else{
midOrder(node.leftChild);
System.out.println("midOrder data:"+node.getData());
midOrder(node.rightChild);
}
}
/*后续遍历*/
public void postOrder(TreeNode node){
if(node==null){
return;
}else{
postOrder(node.leftChild);
postOrder(node.rightChild);
System.out.println("postOrder data:"+node.getData());
}
}
/*前序遍历--非迭代方式--堆栈思想,压栈,弹栈*/
public void nonRecOrder((TreeNode node)){
if(node==null){
return;
}
Stack<TreeNode> stack=new Stack<TreeNode>();
stack.push(node);
while(!stack.isEmpty()){
//出栈进栈
TreeNode n=stack.pop();
System.out.println("nonRecOrder data:"+n.getData());
if(n.rightChild!=null){
stack.push(n.rightChild);
}
if(n.leftChild!=null){
stack.push(n.leftChild);
}
}
}
}
public static void main (String args[]){
BinaryTree binaryTree=new BinaryTree();
binaryTree.createBinaryTree();
int height=binaryTree.getHeight();
//System.out.println("treeHeight:"+height);
int size=binaryTree.getSize();
//System.out.println("treeSize:"+size);
binaryTree.preOrder(binaryTree.root); //前序遍历测试
binaryTree.midOrder(binaryTree.root); //中序遍历测试
binaryTree.postOrder(binaryTree.root); //后序遍历测试
binaryTree.nonRecOrder(binaryTree.root);//堆栈方式优化前序遍历方法测试
}
}
java 实现二叉树的源码实现
猜你喜欢
转载自blog.csdn.net/taotaobaobei/article/details/80445947
今日推荐
周排行