本文共 2880 字,大约阅读时间需要 9 分钟。
class BinaryTree{ //二叉树有必须有根节点 private HeroNode root; public BinaryTree(HeroNode root) { this.root = root; } public BinaryTree() { } //判定当前节点是否为空 public boolean isEmpty(){ if (root == null){ return false; }else{ return true; } } //根节点为二叉树必需的元素,所以必须有根节点才能够创建 //和hashTab类似,头应该有总览调用各个方法,而不是由各个节点调用 public void preOrder(){ if (isEmpty()){ System.out.println("当前树为空,无法遍历"); }else{ root.preOrder(); } } public void minOrder(){ if (isEmpty()){ System.out.println("当前树为空,无法遍历"); }else{ root.midOrder(); } } public void postOrder(){ if (isEmpty()){ System.out.println("当前树为空,无法遍历"); }else{ root.postOrder(); } }}class HeroNode{ private int heroNo; private String heroName; HeroNode left; HeroNode right; public HeroNode(int heroNo, String heroName) { this.heroNo = heroNo; this.heroName = heroName; } public HeroNode getLeft() { return left; } public HeroNode getRight() { return right; } public void setLeft(HeroNode left) { this.left = left; } public void setRight(HeroNode right) { this.right = right; } @Override public String toString() { return "HeroNode{" + "heroNo=" + heroNo + ", heroName='" + heroName + '\'' + '}'; } public void preOrder(){ System.out.println(this); if(this.left != null){ this.left.preOrder(); } if (this.right != null){ this.right.preOrder(); } } public void midOrder(){ if(this.left != null){ this.left.midOrder(); } System.out.println(this); if (this.right != null){ this.right.midOrder(); } } public void postOrder(){ if(this.left != null){ this.left.postOrder(); } if (this.right != null){ this.right.postOrder(); } System.out.println(this); }
转载地址:http://jqgpb.baihongyu.com/