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);
    	}
    }
    
  • 相关阅读:
    @media screen针对不同移动设备-响应式设计
    闭包的一些例子
    es6 新关键字const
    es6 新关键字let
    Unity 多屏(分屏)显示,Muti_Display
    小米手机常用操作
    Charles使用笔记
    AKKA学习笔记
    Gatling-Session
    Scala学习笔记-6-其他
  • 原文地址:https://www.cnblogs.com/yoyohong/p/5657314.html
Copyright © 2011-2022 走看看