zoukankan      html  css  js  c++  java
  • java二叉树的实现和遍历

    /*
     * Java实现二叉树
     */
    public class BinaryTree {
    
    	int treeNode;
    	BinaryTree leftTree;
    	BinaryTree rightTree;
    	
    	public BinaryTree(int Data) {
    		// TODO Auto-generated constructor stub
    		treeNode=Data;
    		leftTree=null;
    		rightTree=null;
    	}
    	
    	public void insert(BinaryTree node,int data) {
    		if(data >node.treeNode){
    			if(node.rightTree==null){
    				rightTree=new BinaryTree(data);
    			}else{
    				this.insert(node.rightTree, data);
    			}
    		}else{
    			if (node.leftTree==null) {
    				leftTree=new BinaryTree(data);
    			}else{
    				this.insert(node.leftTree, data);
    			}
    		}
    	}
    }
    
    /*
     * 对定义二叉树的,先序遍历,中序遍历,后序遍历
     */
    public class BinaryTreeOrder {
    
    	public static void preOrder(BinaryTree root) { // 先序遍历
    		if (root != null) {
    			System.out.print(root.treeNode + "-");
    			preOrder(root.leftTree);
    			preOrder(root.rightTree);
    		}
    	}
    
    	public static void inOrder(BinaryTree root) { // 中序遍历
    
    		if (root != null) {
    			inOrder(root.leftTree);
    			System.out.print(root.treeNode + "--");
    			inOrder(root.rightTree);
    		}
    	}
    
    	public static void postOrder(BinaryTree root) { // 后序遍历
    
    		if (root != null) {
    			postOrder(root.leftTree);
    			postOrder(root.rightTree);
    			System.out.print(root.treeNode + "---");
    		}
    	}
    
    	public static void main(String[] args) {
    		int[] array = { 12, 76, 35, 22, 16, 48, 90, 46, 9, 40 };
    		BinaryTree root = new BinaryTree(array[0]); // 创建二叉树
    		for (int i = 1; i < array.length; i++) {
    			root.insert(root, array[i]); // 向二叉树中插入数据
    		}
    		System.out.println("先序遍历:");
    		preOrder(root);
    		System.out.println();
    		System.out.println("中序遍历:");
    		inOrder(root);
    		System.out.println();
    		System.out.println("后序遍历:");
    		postOrder(root);
    	}
    }
    
  • 相关阅读:
    九度OJ 1154:Jungle Roads(丛林路径) (最小生成树)
    九度OJ 1153:括号匹配问题 (DP)
    九度OJ 1152:点菜问题 (01背包、DP)
    九度OJ 1151:位操作练习 (位操作)
    数论——素数算法
    wubi安装ubuntu-12.04.3
    快速FQ
    linux下的软硬链接区别
    死锁问题总结
    windows下用XShell远程ubuntu时连接失败
  • 原文地址:https://www.cnblogs.com/yoyohong/p/5657314.html
Copyright © 2011-2022 走看看