A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 王震阳老师   /  2014-7-31 11:09  /  15908 人查看  /  238 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文


挺好:
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.Stack;

  5. /**
  6. * ①用Java代码模拟实现一个二叉树结构②创建该二叉树③遍历该二叉树。
  7. *
  8. * @author Administrator TODO
  9. */
  10. class DemoTree {
  11.         public static void main(String[] args) throws IOException {
  12.                 int value;
  13.                 // 创建树对象
  14.                 Tree theTree = new Tree();
  15.                 // 添加元素
  16.                 theTree.insert(50);
  17.                 theTree.insert(75);
  18.                 theTree.insert(12);
  19.                 theTree.insert(37);
  20.                 theTree.insert(43);
  21.                 theTree.insert(30);
  22.                 theTree.insert(33);
  23.                 theTree.insert(87);
  24.                 theTree.insert(93);
  25.                 theTree.insert(97);
  26.                 theTree.insert(50);
  27.                 while (true) {
  28.                         System.out.println("a.查看树结构。");
  29.                         System.out.println("b.遍历树。");
  30.                         System.out.println("请输入a,b");
  31.                         int choice = getChar();
  32.                         switch (choice) {
  33.                         // 查看树结构
  34.                         case 'a':
  35.                                 theTree.displayTree();
  36.                                 break;
  37.                         case 'b':
  38.                                 System.out.println("1.前序遍历:");
  39.                                 System.out.println("2,中序遍历");
  40.                                 System.out.println("3.后序遍历");
  41.                                 System.out.println("请选择1,2,3");
  42.                                 value = getInt();
  43.                                 theTree.traverse(value);
  44.                                 break;
  45.                         default:
  46.                                 System.out.println("格式不正確\n");
  47.                         }
  48.                 }
  49.         }

  50.         public static char getChar() throws IOException {
  51.                 String s = getString();
  52.                 return s.charAt(0);
  53.         }

  54.         public static String getString() throws IOException {
  55.                 InputStreamReader isr = new InputStreamReader(System.in);
  56.                 BufferedReader br = new BufferedReader(isr);
  57.                 String s = br.readLine();
  58.                 return s;
  59.         }

  60.         public static int getInt() throws IOException {
  61.                 String s = getString();
  62.                 return Integer.parseInt(s);
  63.         }

  64. }
  65. //二叉树中每个节点对象
  66. class Node {
  67.         //节点的数据
  68.         public int iData;
  69.         //节点左孩子
  70.         public Node leftChild;
  71.         //节点的右孩子
  72.         public Node rightChild;
  73.         public void displayNode(){
  74.         }
  75. }
  76. //二叉树的结构对象
  77. class Tree {
  78.         //叉树的根节点
  79.         private Node root;
  80.         public Tree(){
  81.                 root = null;
  82.         }
  83.         /**
  84.          * 添加元素
  85.          * @param id 节点的值
  86.          */
  87.         public void insert(int id){
  88.                 //创建新节点
  89.                 Node newNode = new Node();
  90.                 newNode.iData = id;
  91.                 //如果树是空的,就将新节点作为根
  92.                 if(root == null){
  93.                         root = newNode;
  94.                 }
  95.                 //否则,作为根的孩子
  96.                 else{
  97.                         Node current = root;
  98.                         Node parent;
  99.                         while(true){
  100.                                 parent = current;
  101.                                 //如果节点的值小于父节点的值并父节点没有左孩子,它就作为父节点左孩子
  102.                                 if(id < current.iData){
  103.                                         current = current.leftChild;
  104.                                         if(current ==null){
  105.                                                 parent.leftChild = newNode;
  106.                                                 return;
  107.                                                
  108.                                         }
  109.                                 }
  110.                                 //如果节点的值大于父节点的值并父节点没有右孩子,它就作为父节点右孩子
  111.                                 if(id > current.iData){
  112.                                         current = current.rightChild;
  113.                                         if(current == null){
  114.                                                 parent.rightChild = newNode;
  115.                                                 return;
  116.                                         }
  117.                                 }
  118.                                 //否则节点值等于父节点的值,直接返回
  119.                                 else{
  120.                                         return;
  121.                                 }
  122.                         }
  123.                 }
  124.         }
  125.         /**
  126.          * (内部)遍历树
  127.          * @param traverseType 输入的数字
  128.          */
  129.         public void traverse(int traverseType){
  130.                
  131.                 switch(traverseType){
  132.                
  133.                 case 1:
  134.                         System.out.println("\n前序遍历:");
  135.                         preOrder(root);
  136.                         break;
  137.                 case 2:
  138.                         System.out.println("\n中序遍历:");
  139.                         inOrder(root);
  140.                         break;
  141.                 case 3:
  142.                         System.out.println("\n后序遍历:");
  143.                         postOrder(root);
  144.                         break;
  145.                         default:
  146.                                 System.out.println("输入不正确");
  147.                 }
  148.                 System.out.println();
  149.         }
  150.         //前序遍历
  151.         private void preOrder(Node localRoot){
  152.                 if(localRoot!=null){
  153.                         System.out.print(localRoot.iData+" ");
  154.                         preOrder(localRoot.leftChild);
  155.                         preOrder(localRoot.rightChild);
  156.                        
  157.                 }
  158.         }
  159.         //中序遍历
  160.         private void inOrder(Node localRoot){
  161.                 if(localRoot!=null){
  162.                         inOrder(localRoot.leftChild);
  163.                         System.out.print(localRoot.iData+" ");
  164.                         inOrder(localRoot.rightChild);
  165.                        
  166.                 }
  167.         }
  168.         //后序遍历
  169.         private void postOrder(Node localRoot){
  170.                 if(localRoot!=null){
  171.                         postOrder(localRoot.leftChild);
  172.                         postOrder(localRoot.rightChild);
  173.                         System.out.print(localRoot.iData+" ");
  174.                        
  175.                 }
  176.         }
  177.         /**
  178.          * 展示树结构的排列方式
  179.          */
  180.         public void displayTree(){
  181.                 //创建一个栈
  182.                 Stack globalStack = new Stack();
  183.                 //现将树压栈
  184.                 globalStack.push(root);
  185.                 //树中的节点数减1
  186.                 int nBlanks = 32;
  187.                 boolean isRowEmpty =false;
  188.                 System.out.println("-------------------------------------------");
  189.                 while(isRowEmpty == false){
  190.                         Stack localStack = new Stack();
  191.                         isRowEmpty = true;
  192.                         for(int j=0;j<nBlanks;j++){
  193.                                 System.out.print(" ");
  194.                                
  195.                         }
  196.                         while(globalStack.isEmpty() == false){
  197.                                 Node temp = (Node)globalStack.pop();
  198.                                 if(temp!=null){
  199.                                         System.out.print(temp.iData);
  200.                                         localStack.push(temp.leftChild);
  201.                                         localStack.push(temp.rightChild);
  202.                                         if(temp.leftChild !=null||temp.rightChild !=null)
  203.                                                 isRowEmpty = false;
  204.                                 }
  205.                                 else{
  206.                                         System.out.print("--");
  207.                                         localStack.push(null);
  208.                                         localStack.push(null);
  209.                                        
  210.                                 }
  211.                                 for(int j=0;j<nBlanks*2-2;j++)
  212.                                         System.out.print(" ");
  213.                         }
  214.                         System.out.println();
  215.                         System.out.println();
  216.                         nBlanks /= 2;
  217.                         while(localStack.isEmpty()==false)
  218.                                 globalStack.push(localStack.pop());
  219.                 }
  220.                 System.out.println("-------------------------------------");
  221.         }
  222. }
复制代码
回复 使用道具 举报

挺好:
  1. package com.itheima.TechnologyScore;


  2. /**
  3. * Description: 创建二叉树,并遍历,按下面的样子建二叉树
  4. *                       1
  5. *         2                           3
  6. *   4          5                6           7
  7. *8     9    10    11         12   13     14   15
  8. * @author hzChen
  9. * @date 2014-8-2
  10. */

  11. public class BinaryTreeTest
  12. {

  13.     public static void main(String[] args) {
  14.         Integer[] intArray = new Integer[15];
  15.         for (int i = 0; i < 15; i++) {
  16.             intArray[i] = i + 1;
  17.         }
  18.         //写的二叉树构造不限制顺序,不过为了看起来方便,构造数组从1到15
  19.         //创建一个二叉树
  20.         BinaryTree bt = new BinaryTree(intArray);
  21.         String result = null;
  22.         //前序遍历一个二叉树
  23.         result = bt.preAllBinaryTree(bt.getRootNode(), new StringBuilder()).toString();
  24.         System.err.println(result);
  25.         //中序遍历一个二叉树
  26.         result = bt.middleAllBinaryTree(bt.getRootNode(), new StringBuilder()).toString();
  27.         System.err.println(result);
  28.         //后序遍历一个二叉树
  29.         result = bt.lastAllBinaryTree(bt.getRootNode(), new StringBuilder()).toString();
  30.         System.err.println(result);
  31.     }
  32. }


  33. /**
  34. *
  35. * <p>定义一个二叉树</p>
  36. */
  37. class BinaryTree
  38. {
  39.     /** 根节点 */
  40.     private Node rootNode = new Node();
  41.    
  42.    
  43.     /**构造方法,通过传入的数组创建二叉树*/
  44.     BinaryTree(Integer[] intArray){
  45.         createTree(rootNode, intArray, 0);
  46.     }
  47.    
  48.     /**
  49.      * 功能描述:递归构建二叉树
  50.      * @param parent 父节点
  51.      * @param intArray 完整数组
  52.      * @param index 父节点在数组中的索引值
  53.      */
  54.     private void createTree(Node parent, Integer[] intArray, Integer index){
  55.         parent.setNodeValue(intArray[index]);
  56.         if(2 * index + 1 < intArray.length){//存在左叶子
  57.             Node leftNode = new Node(intArray[2 * index + 1]);
  58.             parent.setLeftNode(leftNode);
  59.             createTree(leftNode, intArray, 2 * index + 1);
  60.         }
  61.         if(2 * index + 2 < intArray.length){//存在右叶子
  62.             Node rightNode = new Node(intArray[2 * index + 2]);
  63.             parent.setRightNode(rightNode);
  64.             createTree(rightNode, intArray, 2 * index + 2);
  65.         }
  66.         
  67.         
  68.     }
  69.    
  70.     /** 递归遍历而二叉树 前序 根左右 */
  71.     public StringBuilder preAllBinaryTree(Node parent, StringBuilder sb){
  72.         if(null != parent){//到叶子节点停止递归
  73.             sb.append(parent.getNodeValue()+" ");
  74.             preAllBinaryTree(parent.getLeftNode(), sb);
  75.             preAllBinaryTree(parent.getRightNode(), sb);
  76.         }
  77.         return sb;
  78.     }
  79.    
  80.     /** 递归遍历而二叉树 中序 左根右 */
  81.     public StringBuilder middleAllBinaryTree(Node parent, StringBuilder sb) {
  82.         if(null != parent){//到叶子节点停止递归
  83.             preAllBinaryTree(parent.getLeftNode(), sb);
  84.             sb.append(parent.getNodeValue()+" ");
  85.             preAllBinaryTree(parent.getRightNode(), sb);
  86.         }
  87.         return sb;
  88.     }
  89.    
  90.     /** 递归遍历而二叉树 后序 左右根 */
  91.     public StringBuilder lastAllBinaryTree(Node parent, StringBuilder sb) {
  92.         if(null != parent){//到叶子节点停止递归
  93.             preAllBinaryTree(parent.getLeftNode(), sb);
  94.             preAllBinaryTree(parent.getRightNode(), sb);
  95.             sb.append(parent.getNodeValue()+" ");
  96.         }
  97.         return sb;
  98.     }
  99.     public Node getRootNode() {
  100.         return rootNode;
  101.     }
  102.     public void setRootNode(Node rootNode) {
  103.         this.rootNode = rootNode;
  104.     }
  105. }


  106. /**
  107. * <p>定义节点</p>
  108. */
  109. class Node
  110. {
  111.     private Node leftNode;
  112.     private Node rightNode;
  113.     private Integer nodeValue;

  114.     Node(){
  115.     }
  116.     // 构造方法
  117.     Node(Integer nodeValue)
  118.     {
  119.         this.leftNode = null;
  120.         this.rightNode = null;
  121.         this.nodeValue = nodeValue;
  122.     }

  123.     public Node getLeftNode() {
  124.         return leftNode;
  125.     }
  126.     public void setLeftNode(Node leftNode) {
  127.         this.leftNode = leftNode;
  128.     }
  129.     public Node getRightNode() {
  130.         return rightNode;
  131.     }
  132.     public void setRightNode(Node rightNode) {
  133.         this.rightNode = rightNode;
  134.     }
  135.     public Integer getNodeValue() {
  136.         return nodeValue;
  137.     }
  138.     public void setNodeValue(Integer nodeValue) {
  139.         this.nodeValue = nodeValue;
  140.     }
  141. }

复制代码
回复 使用道具 举报
执笔梦 发表于 2014-8-2 20:22
学习,学习,以前学过,不过差不多都还给老师了,感觉最麻烦的就是泛型了 ...

挺好:
  1. package cc.tree.domain;
  2. /**
  3. * 二叉树只有一个根节点,每个节点最多有两个子树的树结构.分为左,右子树.
  4. *                 对于二叉树的遍历方式一般分为三种先序、中序、后序三种方式
  5. *                         1.先序(根左右)
  6. *                                         若二叉树为空,则不进行任何操作:否则
  7.                        1、访问根结点。
  8.                        2、先序方式遍历左子树。
  9.                        3、先序遍历右子树。
  10.             2.中序(左根右)
  11.                           若二叉树为空,则不进行任何操作:否则
  12.                        1、中序遍历左子树。
  13.                        2、访问根结点。
  14.                        3、中序遍历右子树。
  15.             3.后序(左右根)
  16.                          若二叉树为空,则不进行任何操作:否则
  17.                        1、后序遍历左子树。
  18.                        2、后序遍历右子树。
  19.                        3、放问根结点。
  20. * */
  21. /**
  22. * 二叉树类型
  23. * */
  24. public class BinaryTree<T>{
  25.         /**
  26.          *节点也应该是个类型,而且节点类型应该是包含在二叉树类型中
  27.          * */
  28.         class Node{
  29.                 //左节点
  30.                 private Node leftNode;
  31.                 //右节点
  32.                 private Node rigthNode;
  33.                 //节点的值
  34.                 private T value;
  35.                 /*
  36.                  * 提供一个空的构造方法
  37.                  * */
  38.                 public Node(){
  39.                         super();
  40.                 }
  41.                 /*
  42.                  * 构造一个节点的值为value.
  43.                  * */
  44.                 public Node(T value){
  45.                         this.value = value;
  46.                         leftNode = null;
  47.                         rigthNode = null;
  48.                 }
  49.                 /*
  50.                  * 根据值,左右节点构造一个节点.
  51.                  * */
  52.                 public Node(T value,Node leftNode,Node rithtNode){
  53.                         this.value = value;
  54.                         this.leftNode = leftNode;
  55.                         this.rigthNode = rithtNode;
  56.                 }
  57.                
  58.                 public Node getLeftNode() {
  59.                         return leftNode;
  60.                 }
  61.                
  62.                 public Node getRigthNode() {
  63.                         return rigthNode;
  64.                 }
  65.                
  66.                 public T getValue() {
  67.                         return value;
  68.                 }
  69.                
  70.                 public void setLeftNode(Node leftNode) {
  71.                         this.leftNode = leftNode;
  72.                 }
  73.                
  74.                 public void setRigthNode(Node rigthNode) {
  75.                         this.rigthNode = rigthNode;
  76.                 }
  77.                
  78.                 public void setValue(T value) {
  79.                         this.value = value;
  80.                 }
  81.         }
  82.         /*
  83.          * 测试
  84.          * */
  85.         public static void main(String[] args) {
  86.                 BinaryTree<String> tree = new BinaryTree<String>();
  87.                 tree.infoTree(tree);
  88.         //        tree.CenterIteration(tree.root);
  89.                 tree.beforeIteration(tree.root);
  90.         //        tree.afterIteration(tree.root);
  91.         }
  92.        
  93.         private Node root;
  94.        
  95.         public BinaryTree(){
  96.                 root =null;
  97.         }
  98.         /*
  99.          *后序
  100.          * */
  101.         public void afterIteration(Node targetNode){
  102.                 //如果target为null,则结束方法
  103.                 if(targetNode == null){
  104.                         return;
  105.                 }
  106.                 Node leftNode = targetNode.getLeftNode();
  107.                 Node rightNode = targetNode.getRigthNode();
  108.                 if( leftNode != null){
  109.                         this.beforeIteration(leftNode);
  110.                 }
  111.                 if(rightNode  != null){
  112.                         this.beforeIteration(rightNode);
  113.                 }
  114.                 this.getNodeValue(targetNode);
  115.         }
  116.         /*
  117.          * 前遍历
  118.          * */
  119.         public void beforeIteration(Node targetNode){
  120.                 //如果target为null,则结束方法
  121.                 if(targetNode == null){
  122.                         return;
  123.                 }
  124.                 //打印根节点 和 获取当前节点的左右子树的根节点
  125.                 this.getNodeValue(targetNode);
  126.                 Node leftNode = targetNode.getLeftNode();
  127.                 Node rightNode = targetNode.getRigthNode();
  128.                 if( leftNode != null){
  129.                         this.beforeIteration(leftNode);
  130.                 }
  131.                 if(rightNode  != null){
  132.                         this.beforeIteration(rightNode);
  133.                 }
  134.         }
  135.         /*
  136.          * 中序
  137.          * */
  138.         public void CenterIteration(Node targetNode){
  139.                 //如果target为null,则结束方法
  140.                 if(targetNode == null){
  141.                         return;
  142.                 }
  143.                 Node leftNode = targetNode.getLeftNode();
  144.                 Node rightNode = targetNode.getRigthNode();
  145.                 if( leftNode != null){
  146.                         this.beforeIteration(leftNode);
  147.                 }
  148.                 this.getNodeValue(targetNode);
  149.                 if(rightNode  != null){
  150.                         this.beforeIteration(rightNode);
  151.                 }
  152.         }
  153.         /*
  154.          * 输出当前节点值
  155.          * */
  156.         public void  getNodeValue(Node node){
  157.                 if(node == null){
  158.                         return;
  159.                 }
  160.                 System.out.println(node.getValue());
  161.         }
  162.         public Node getRoot() {
  163.                 return root;
  164.         }
  165.         /*
  166.          * 构造一个BinaryTree,返回根节点
  167.          * */
  168.         public Node infoTree(BinaryTree<String> tree){
  169.                 BinaryTree<String>.Node G = tree.new Node("G", null, null);
  170.                 BinaryTree<String>.Node F = tree.new Node("F", null, null);
  171.                 BinaryTree<String>.Node E = tree.new Node("E", null, G);
  172.                 BinaryTree<String>.Node D = tree.new Node("D", E, F);
  173.                 BinaryTree<String>.Node C = tree.new Node("C", null, null);
  174.                 BinaryTree<String>.Node B = tree.new Node("B", C, D);
  175.                 tree.root = tree.new Node("root", B, null);
  176.              return root;
  177.         }
  178.        
  179.         public void setRoot(Node root) {
  180.                 this.root = root;
  181.         }
  182. }
复制代码
回复 使用道具 举报

挺好:
  1. package com.ymocean;

  2. import java.util.Comparator;

  3. public class BinaryTree<T> {
  4.         private BinaryNode<T> root;

  5.         // 二叉树节点
  6.         private class BinaryNode<T> {
  7.                 private T element;
  8.                 private BinaryNode<T> left;
  9.                 private BinaryNode<T> right;

  10.                 public BinaryNode(T theElement) {
  11.                         element = theElement;
  12.                         left = null;
  13.                         right = null;
  14.                 }

  15.                 public BinaryNode(T theElement, BinaryNode<T> lt, BinaryNode<T> rt) {
  16.                         element = theElement;
  17.                         left = lt;
  18.                         right = rt;
  19.                 }
  20.         }

  21.         private Comparator<? super T> cmp;

  22.         public BinaryTree() {
  23.                 this(null);
  24.         }

  25.         public BinaryTree(Comparator<? super T> c) {
  26.                 root = null;
  27.                 cmp = c;
  28.         }

  29.         // 比较
  30.         private int myCompare(T left, T right) {
  31.                 if (cmp != null) {
  32.                         return cmp.compare(left, right);
  33.                 } else {
  34.                         return ((Comparable) left).compareTo(right);
  35.                 }
  36.         }

  37.         // 创建二叉树
  38.         public void buildTree(T x, BinaryNode<T> t) {
  39.                 if (root == null) {
  40.                         root = new BinaryNode(x);
  41.                 } else {
  42.                         if (myCompare(x, t.element) < 0) {
  43.                                 if (t.left == null) {
  44.                                         t.left = new BinaryNode(x);
  45.                                 } else {
  46.                                         buildTree(x, t.left);
  47.                                 }
  48.                         } else {
  49.                                 if (t.right == null) {
  50.                                         t.right = new BinaryNode(x);
  51.                                 } else {
  52.                                         buildTree(x, t.right);
  53.                                 }
  54.                         }
  55.                 }
  56.         }

  57.         // 前序遍历
  58.         public void preOrder(BinaryNode<T> t) {
  59.                 if (t != null) {
  60.                         System.out.print(t.element + " ");
  61.                         preOrder(t.left);
  62.                         preOrder(t.right);
  63.                 }
  64.         }

  65.         // 中序遍历
  66.         public void inOrder(BinaryNode<T> t) {
  67.                 if (t != null) {
  68.                         inOrder(t.left);
  69.                         System.out.print(t.element + " ");
  70.                         inOrder(t.right);
  71.                 }
  72.         }

  73.         // 后序遍历
  74.         public void postOrder(BinaryNode<T> t) {
  75.                 if (t != null) {
  76.                         postOrder(t.left);
  77.                         postOrder(t.right);
  78.                         System.out.print(t.element + " ");
  79.                 }
  80.         }

  81.         public static void main(String[] args) {
  82.                 int[] a = { 1, 14, 77, 23, 58, 102, 86, 4 };
  83.                 BinaryTree bTree = new BinaryTree();
  84.                 for (int i = 0; i < a.length; i++) {
  85.                         bTree.buildTree(a[i], bTree.root);
  86.                 }
  87.                 System.out.println("前序遍历:");
  88.                 bTree.preOrder(bTree.root);
  89.                 System.out.println("\n");
  90.                 System.out.println("中序遍历:");
  91.                 bTree.inOrder(bTree.root);
  92.                 System.out.println("\n");
  93.                 System.out.println("后序遍历:");
  94.                 bTree.postOrder(bTree.root);
  95.         }
  96. }
复制代码
回复 使用道具 举报
沟门大杏 发表于 2014-8-2 21:57
忘了设管理员权限。再提交一次

挺好:
  1. package asd;

  2. public class Test {

  3.         public static void main(String[] args) {
  4.                
  5.                
  6.         }

  7. }
  8. class Node {
  9. private int value;
  10. private Node left;
  11. private Node right;
  12. // 存储节点
  13. public void store(int value) {
  14. if (this.value > value) {
  15. if (left == null) {
  16. left = new Node();
  17. left.value = value;
  18. } else {
  19. left.store(value);
  20. }
  21. } else {
  22. if (right == null) {
  23. right = new Node();
  24. right.value = value;
  25. } else {
  26. /*right.value = value;*/
  27. right.store(value);
  28. }
  29. }
  30. }
  31. // 查找节点
  32. public boolean find(int value) {
  33. if (this.value == value) {
  34. return true;
  35. } else if (this.value > value) {
  36. if (right == null)
  37. return false;
  38. return right.find(value);
  39. } else {
  40. if (left == null)
  41. return false;
  42. return left.find(value);
  43. }
  44. }
  45. // 前序遍历
  46. public void preList() {
  47. System.out.print(this.value + ">>");
  48. if (left != null)
  49. left.preList();
  50. if (right != null)
  51. right.preList();
  52. }
  53. // 中序遍历
  54. public void middleList() {
  55. if (left != null)
  56. left.middleList();
  57. System.out.print(this.value + ">>");
  58. if (right != null)
  59. right.middleList();
  60. }
  61. // 后序遍历
  62. public void afterList() {
  63. if (left != null)
  64. left.afterList();
  65. if (right != null)
  66. right.afterList();
  67. System.out.print(this.value + ">>");
  68. }
  69. /**
  70. * @return the value
  71. */
  72. public int getValue() {
  73. return value;
  74. }
  75. /**
  76. * @param value the value to set
  77. */
  78. public void setValue(int value) {
  79. this.value = value;
  80. }
  81. }
复制代码
回复 使用道具 举报

挺好:
  1. import java.util.LinkedList;

  2. /*
  3. * ①用Java代码模拟实现一个二叉树结构
  4. * ②创建该二叉树
  5. * ③遍历该二叉树。
  6. */
  7. public class TreeTest {

  8.         public static void main(String[] args)throws Exception {
  9.                 int[] arr={4,8,6,9,5,2,7,1,3};
  10.                 //使用数组构建二叉树
  11.                 BinaryTree tree=new BinaryTree(arr);
  12.                
  13.                 //遍历二叉树
  14.                 //tree.preOrderTraverse();//先序遍历               
  15.                 //tree.inOrderTraverse();//中序遍历
  16.                 //tree.postOrderTraverse();//后序遍历
  17.                 tree.levelTraverse();//按层次遍历
  18.         }

  19. }
  20. //自定义二叉树类
  21. class BinaryTree{
  22.         //根节点成员变量
  23.         private Node root;
  24.        
  25.         //无参构造方法
  26.         public BinaryTree(){
  27.                 root=null;
  28.         }
  29.         //使用一个数组来构造二叉树
  30.         public BinaryTree(int[] arr){
  31.                 for (int i:arr) {
  32.                         root=insertNode(root,i);
  33.                 }
  34.         }
  35.        
  36.         /*插入节点,并且根据节点的值来判断插入方向。
  37.         当值小于或等于当前节点的值,则插入当前节点的左侧;
  38.         否则,插入当前节点的右侧。
  39.         每次从根节点开始递归比较。*/
  40.         private Node insertNode(Node node,int value){
  41.                 if(node==null)
  42.                         node=new Node(value);
  43.                 else{
  44.                         if(value <= node.getValue())
  45.                                 node.setLeft(insertNode(node.getLeft(),value));
  46.                         else
  47.                                 node.setRight(insertNode(node.getRight(),value));       
  48.                 }       
  49.                 return node;
  50.         }
  51.        
  52.         //遍历二叉树
  53.         //先序遍历
  54.         public void preOrderTraverse(){
  55.                 preOrderTraverse1(root);
  56.         }
  57.         //中序遍历
  58.         public void inOrderTraverse(){
  59.                 inOrderTraverse1(root);
  60.         }
  61.         //后序遍历
  62.         public void postOrderTraverse(){
  63.                 postOrderTraverse1(root);
  64.         }
  65.         //按层次遍历
  66.         public void levelTraverse(){
  67.                 levelTraverse1(root);
  68.         }
  69.        
  70.         //先序遍历的具体实现
  71.         private void preOrderTraverse1(Node node){
  72.                 if(node!=null){
  73.                         System.out.println(node.getValue());
  74.                         preOrderTraverse1(node.getLeft());
  75.                         preOrderTraverse1(node.getRight());
  76.                 }
  77.         }
  78.         //中序遍历的具体实现
  79.         private void inOrderTraverse1(Node node){
  80.                 if(node!=null){
  81.                         inOrderTraverse1(node.getLeft());
  82.                         System.out.println(node.getValue());
  83.                         inOrderTraverse1(node.getRight());
  84.                 }
  85.         }
  86.         //后序遍历的具体实现
  87.         private void postOrderTraverse1(Node node){
  88.                 if(node!=null){
  89.                         postOrderTraverse1(node.getLeft());
  90.                         postOrderTraverse1(node.getRight());
  91.                         System.out.println(node.getValue());
  92.                 }
  93.         }
  94.         //按层次遍历的具体实现
  95.         private void levelTraverse1(Node node){
  96.                 LinkedList<Node> queue=new LinkedList<Node>();
  97.                 queue.offerLast(node);
  98.                 while(!queue.isEmpty()){
  99.                         Node temp=queue.pollFirst();
  100.                         if(temp!=null){
  101.                                 System.out.println(temp.getValue());
  102.                                 queue.offerLast(temp.getLeft());
  103.                                 queue.offerLast(temp.getRight());
  104.                         }
  105.                 }
  106.         }
  107. }
  108. //节点类
  109. class Node{
  110.         //每个节点有三个属性:节点值、左子节点、右子节点
  111.         private Node left;
  112.         private Node right;
  113.         private int value;
  114.        
  115.         //无参构造方法
  116.         public Node(){}
  117.         //通过构造方法初始化节点值
  118.         public Node(int value){
  119.                 this(null,null,value);
  120.         }
  121.         //通过构造方法初始化节点值、左子节点、右子节点
  122.         public Node(Node left,Node right,int value){
  123.                 this.left=left;
  124.                 this.right=right;
  125.                 this.value=value;
  126.         }
  127.        
  128.         //获取、设置左子节点
  129.         public Node getLeft(){
  130.                 return left;
  131.         }
  132.         public void setLeft(Node left){
  133.                 this.left=left;
  134.         }
  135.         //获取、设置右子节点
  136.         public Node getRight(){
  137.                 return right;
  138.         }
  139.         public void setRight(Node right){
  140.                 this.right=right;
  141.         }
  142.         //获取、设置节点值
  143.         public int getValue() {
  144.                 return value;
  145.         }
  146.         public void setValue(int value) {
  147.                 this.value = value;
  148.         }       
  149. }
复制代码
回复 使用道具 举报
止询初衷 发表于 2014-8-2 00:17
不好意思,理解错了。。

挺好:
  1. package a.TreeSetD;
  2. import java.util.Stack;  
  3.   
  4. public class BinaryTree {  
  5.   
  6.       
  7.     private TreeNode root=null;  
  8.       
  9.     public BinaryTree(){  
  10.         root=new TreeNode(1,"rootNode(A)");  
  11.     }  
  12.       
  13.     /**
  14.      * 创建一棵二叉树
  15.      * <pre>
  16.      *           A
  17.      *     B          C
  18.      *  D     E            F
  19.      *  </pre>
  20.      * @param root
  21.      * @author WWX
  22.      */  
  23.     public void createBinTree(TreeNode root){  
  24.         TreeNode newNodeB = new TreeNode(2,"B");  
  25.         TreeNode newNodeC = new TreeNode(3,"C");  
  26.         TreeNode newNodeD = new TreeNode(4,"D");  
  27.         TreeNode newNodeE = new TreeNode(5,"E");  
  28.         TreeNode newNodeF = new TreeNode(6,"F");  
  29.         root.leftChild=newNodeB;  
  30.         root.rightChild=newNodeC;  
  31.         root.leftChild.leftChild=newNodeD;  
  32.         root.leftChild.rightChild=newNodeE;  
  33.         root.rightChild.rightChild=newNodeF;  
  34.     }  
  35.       
  36.       
  37.     public boolean isEmpty(){  
  38.         return root==null;  
  39.     }  
  40.   
  41.     //树的高度  
  42.     public int height(){  
  43.         return height(root);  
  44.     }  
  45.       
  46.     //节点个数  
  47.     public int size(){  
  48.         return size(root);  
  49.     }  
  50.       
  51.       
  52.     private int height(TreeNode subTree){  
  53.         if(subTree==null)  
  54.             return 0;//递归结束:空树高度为0  
  55.         else{  
  56.             int i=height(subTree.leftChild);  
  57.             int j=height(subTree.rightChild);  
  58.             return (i<j)?(j+1):(i+1);  
  59.         }  
  60.     }  
  61.       
  62.     private int size(TreeNode subTree){  
  63.         if(subTree==null){  
  64.             return 0;  
  65.         }else{  
  66.             return 1+size(subTree.leftChild)  
  67.                     +size(subTree.rightChild);  
  68.         }  
  69.     }  
  70.       
  71.     //返回双亲结点  
  72.     public TreeNode parent(TreeNode element){  
  73.         return (root==null|| root==element)?null:parent(root, element);  
  74.     }  
  75.       
  76.     public TreeNode parent(TreeNode subTree,TreeNode element){  
  77.         if(subTree==null)  
  78.             return null;  
  79.         if(subTree.leftChild==element||subTree.rightChild==element)  
  80.             //返回父结点地址  
  81.             return subTree;  
  82.         TreeNode p;  
  83.         //现在左子树中找,如果左子树中没有找到,才到右子树去找  
  84.         if((p=parent(subTree.leftChild, element))!=null)  
  85.             //递归在左子树中搜索  
  86.             return p;  
  87.         else  
  88.             //递归在右子树中搜索  
  89.             return parent(subTree.rightChild, element);  
  90.     }  
  91.       
  92.     public TreeNode getLeftChildNode(TreeNode element){  
  93.         return (element!=null)?element.leftChild:null;  
  94.     }  
  95.       
  96.     public TreeNode getRightChildNode(TreeNode element){  
  97.         return (element!=null)?element.rightChild:null;  
  98.     }  
  99.       
  100.     public TreeNode getRoot(){  
  101.         return root;  
  102.     }  
  103.       
  104.     //在释放某个结点时,该结点的左右子树都已经释放,  
  105.     //所以应该采用后续遍历,当访问某个结点时将该结点的存储空间释放  
  106.     public void destroy(TreeNode subTree){  
  107.         //删除根为subTree的子树  
  108.         if(subTree!=null){  
  109.             //删除左子树  
  110.             destroy(subTree.leftChild);  
  111.             //删除右子树  
  112.             destroy(subTree.rightChild);  
  113.             //删除根结点  
  114.             subTree=null;  
  115.         }  
  116.     }  
  117.       
  118.     public void traverse(TreeNode subTree){  
  119.         System.out.println("key:"+subTree.key+"--name:"+subTree.data);;  
  120.         traverse(subTree.leftChild);  
  121.         traverse(subTree.rightChild);  
  122.     }  
  123.       
  124.     //前序遍历  
  125.     public void preOrder(TreeNode subTree){  
  126.         if(subTree!=null){  
  127.             visted(subTree);  
  128.             preOrder(subTree.leftChild);  
  129.             preOrder(subTree.rightChild);  
  130.         }  
  131.     }  
  132.       
  133.     //中序遍历  
  134.     public void inOrder(TreeNode subTree){  
  135.         if(subTree!=null){  
  136.             inOrder(subTree.leftChild);  
  137.             visted(subTree);  
  138.             inOrder(subTree.rightChild);  
  139.         }  
  140.     }  
  141.       
  142.     //后续遍历  
  143.     public void postOrder(TreeNode subTree) {  
  144.         if (subTree != null) {  
  145.             postOrder(subTree.leftChild);  
  146.             postOrder(subTree.rightChild);  
  147.             visted(subTree);  
  148.         }  
  149.     }  
  150.       
  151.     //前序遍历的非递归实现  
  152.     public void nonRecPreOrder(TreeNode p){  
  153.         Stack<TreeNode> stack=new Stack<TreeNode>();  
  154.         TreeNode node=p;  
  155.         while(node!=null||stack.size()>0){  
  156.             while(node!=null){  
  157.                 visted(node);  
  158.                 stack.push(node);  
  159.                 node=node.leftChild;  
  160.             }  
  161.           while(stack.size()>0){  
  162.                 node=stack.pop();  
  163.                 node=node.rightChild;  
  164.             }   
  165.         }  
  166.     }  
  167.       
  168.     //中序遍历的非递归实现  
  169.     public void nonRecInOrder(TreeNode p){  
  170.         Stack<TreeNode> stack =new Stack<BinaryTree.TreeNode>();  
  171.         TreeNode node =p;  
  172.         while(node!=null||stack.size()>0){  
  173.             //存在左子树  
  174.             while(node!=null){  
  175.                 stack.push(node);  
  176.                 node=node.leftChild;  
  177.             }  
  178.             //栈非空  
  179.             if(stack.size()>0){  
  180.                 node=stack.pop();  
  181.                 visted(node);  
  182.                 node=node.rightChild;  
  183.             }  
  184.         }  
  185.     }  
  186.       
  187.     //后序遍历的非递归实现  
  188.     public void noRecPostOrder(TreeNode p){  
  189.         Stack<TreeNode> stack=new Stack<BinaryTree.TreeNode>();  
  190.         TreeNode node =p;  
  191.         while(p!=null){  
  192.             //左子树入栈  
  193.             for(;p.leftChild!=null;p=p.leftChild){  
  194.                 stack.push(p);  
  195.             }  
  196.             //当前结点无右子树或右子树已经输出  
  197.             while(p!=null&&(p.rightChild==null||p.rightChild==node)){  
  198.                 visted(p);  
  199.                 //纪录上一个已输出结点  
  200.                 node =p;  
  201.                 if(stack.empty())  
  202.                     return;  
  203.                 p=stack.pop();  
  204.             }  
  205.             //处理右子树  
  206.             stack.push(p);  
  207.             p=p.rightChild;  
  208.         }  
  209.     }  
  210.     public void visted(TreeNode subTree){  
  211.         subTree.isVisted=true;  
  212.         System.out.println("key:"+subTree.key+"--name:"+subTree.data);;  
  213.     }  
  214.       
  215.       
  216.     /**
  217.      * 二叉树的节点数据结构
  218.      * @author WWX
  219.      */  
  220.     private class  TreeNode{  
  221.         private int key=0;  
  222.         private String data=null;  
  223.         private boolean isVisted=false;  
  224.         private TreeNode leftChild=null;  
  225.         private TreeNode rightChild=null;  
  226.          
  227.         public TreeNode(){}  
  228.          
  229.         /**
  230.          * @param key  层序编码
  231.          * @param data 数据域
  232.          */  
  233.         public TreeNode(int key,String data){  
  234.             this.key=key;  
  235.             this.data=data;  
  236.             this.leftChild=null;  
  237.             this.rightChild=null;  
  238.         }  
  239.   
  240.   
  241.     }  
  242.       
  243.       
  244.     //测试  
  245.     public static void main(String[] args) {  
  246.         BinaryTree bt = new BinaryTree();  
  247.         bt.createBinTree(bt.root);  
  248.         System.out.println("the size of the tree is " + bt.size());  
  249.         System.out.println("the height of the tree is " + bt.height());  
  250.          
  251.         System.out.println("*******(前序遍历)[ABDECF]遍历*****************");  
  252.         bt.preOrder(bt.root);  
  253.          
  254.         System.out.println("*******(中序遍历)[DBEACF]遍历*****************");  
  255.         bt.inOrder(bt.root);  
  256.          
  257.         System.out.println("*******(后序遍历)[DEBFCA]遍历*****************");  
  258.         bt.postOrder(bt.root);  
  259.          
  260.         System.out.println("***非递归实现****(前序遍历)[ABDECF]遍历*****************");  
  261.         bt.nonRecPreOrder(bt.root);  
  262.          
  263.         System.out.println("***非递归实现****(中序遍历)[DBEACF]遍历*****************");  
  264.         bt.nonRecInOrder(bt.root);  
  265.          
  266.         System.out.println("***非递归实现****(后序遍历)[DEBFCA]遍历*****************");  
  267.         bt.noRecPostOrder(bt.root);  
  268.     }  
  269. }  
复制代码
回复 使用道具 举报

哦哦。采学习完集合,想的有点简单,我会继续努力的
回复 使用道具 举报
.Mч┞尛__洋 发表于 2014-8-2 10:52
阳哥     抱拳了 !!!!!

挺好:
  1. public class CreatBiTree {
  2. /*
  3. * 题目:①用Java代码模拟实现一个二叉树结构②创建该二叉树③遍历该二叉树。
  4. *
  5. * 思路:二叉树:一种树状结构,一棵二叉树的“结点”(Node)最多只能拥有2个子结点,也就是度小于或等于2。
  6. *     1)二叉树的结点个数是有限,而且可以没有结点。
  7. *     2)一棵二叉树的树根下可以分为两个子树称为“左子树”(Left Subtree)和“右子树”(Right Subtree)
  8. *     3)前、中、后序遍历。
  9. */
  10.         private Node root;
  11.        
  12.         /*
  13.          * 创建二叉树节点,利用内部类方式。
  14.          * @author lhy
  15.          */
  16.         private class Node{
  17.                 private Node left;//定义左节点
  18.                 private Node right;//定义右节点
  19.                 private int value;//节点值。
  20.                 public Node(int value){
  21.                         this.left = null;
  22.                         this.right = null;
  23.                         this.value = value;
  24.                 }
  25.         }
  26.        
  27.         public CreatBiTree(){
  28.                 root = null;
  29.         }
  30.        
  31.         /*
  32.          * 递归创建二叉树,不过多解释了,直接上代码。
  33.          */
  34.         public void buildTree(Node node,int value){
  35.                 if(root == null){
  36.                         root = new Node(value);
  37.                 }else{
  38.                         if(value < node.value){
  39.                                 if(node.left == null){
  40.                                         node.left = new Node(value);
  41.                                 }else{
  42.                                         buildTree(node.left,value);
  43.                                 }
  44.                         }else{
  45.                                 if(node.right == null){
  46.                                         node.right = new Node(value);
  47.                                 }else{
  48.                                         buildTree(node.right,value);
  49.                                 }
  50.                         }
  51.                 }
  52.         }
  53.        
  54.         /*
  55.          * 前序遍历也称先序遍历。
  56.          */
  57.         public void preOrder(Node node){
  58.                 if(node != null){
  59.                         System.out.print(node.value+" ");
  60.                         preOrder(node.left);
  61.                         preOrder(node.right);
  62.                 }
  63.         }
  64.        
  65.         /*
  66.          * 中序遍历
  67.          */
  68.         public void inOrder(Node node){
  69.                 if(node != null){
  70.                         inOrder(node.left);
  71.                         System.out.print(node.value+" ");
  72.                         inOrder(node.right);
  73.                 }
  74.         }
  75.        
  76.         /*
  77.          * 后序遍历
  78.          */
  79.         public void postOrder(Node node){
  80.                 if(node != null){
  81.                         postOrder(node.left);
  82.                         postOrder(node.right);
  83.                         System.out.print(node.value+" ");
  84.                 }
  85.         }
  86.        
  87.         public static void main(String[] args) {
  88.                 int[] a = {1,2,3,4,5,6,7,8,9,10,11,12,13,14};
  89.                 CreatBiTree bTree = new CreatBiTree();
  90.                 for (int i = 0; i < a.length; i++) {
  91.                         bTree.buildTree(bTree.root, a[i]);
  92.                 }
  93.                 System.out.println("先序遍历的结果是:");
  94.                 bTree.preOrder(bTree.root);
  95.                 System.out.println("\n中序遍历的结果是:");
  96.                 bTree.inOrder(bTree.root);
  97.                 System.out.println("\n后序遍历的结果是:");
  98.                 bTree.postOrder(bTree.root);
  99.         }

  100. }
复制代码
回复 使用道具 举报
就业指导-王震阳老师 发表于 2014-8-4 22:08
答案很给力,请大家参考:
自定义二叉树类:

学习了,想到添加的数据要实现Comparable,也想到根据节点值大小添加到左右子树,不过最后还是败给泛型了,就没有实现出来,
回复 使用道具 举报
来试试看看
回复 使用道具 举报
没想到没有上榜...伤心了
回复 使用道具 举报
阳哥要求实现添加和遍历你们都干了什么!!!!呜呜呜~~~太不公平了
回复 使用道具 举报
额 黑马不能上网  来次论坛不容易啊
回复 使用道具 举报
呵呵!! 貌似都挺牛掰的样子
回复 使用道具 举报
虽然答案都有了,我也发一个我写的

Test.zip

1.56 KB, 下载次数: 72

评分

参与人数 1技术分 +2 收起 理由
王震阳老师 + 2 赞一个!

查看全部评分

回复 使用道具 举报
领取题目!!!
回复 使用道具 举报
又来看一遍!
回复 使用道具 举报
管理滔哥给我说我连续刷帖,减了50黑马币,可是我没有,好伤心!!!!
回复 使用道具 举报
来看看什么类型的
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马