• java操作二叉树


    /*
    题目:用java语言创建二叉树,完成二叉树的建立和遍历;
    
    */
    import java.util.Scanner;
    class  BinaryTreeDemo
    {
    	public static void main(String[] args) 
    	{
    		Node binaryNode = new Node();
    		BinaryTree binaryTree = new BinaryTree(binaryNode);
    		System.out.println("创建二叉树:");
    		binaryNode = binaryTree.createBinaryTree();
    		System.out.println("前序遍历:");
    		binaryTree.PreTree(binaryNode);
    		System.out.println();
    		System.out.println("中序遍历");
    		binaryTree.InOrderTree(binaryNode);
    		System.out.println();
    		System.out.println("后序遍历");
    		binaryTree.PostOrderTree(binaryNode);
    
    	}
    }
    
    /*
    二叉树特点:
    最多有两个节点
    */
    class Node
    {
    	// 存储二叉树节点值
    	public int data;
    	// 左节点
    	public Node leftChild;
    	// 右节点
    	public Node rightChild;
    }
    
    class BinaryTree
    {
    	//创建一个父节点
    	private Node rootNode;
    	public BinaryTree(Node rootNode)
    	{
    		this.rootNode = rootNode;
    	}
    
    	//  按前序建立二叉树
    	public Node createBinaryTree()
    	{
    		Node temp = new Node();
    		Scanner sc = new Scanner(System.in);
    		int value = sc.nextInt();
    		if(value == 0)		//输入0表示该节点为空
    		{
    			temp = null;
    		}
    		else
    		{
    			temp.data = value;
    			temp.leftChild = createBinaryTree();
    			temp.rightChild = createBinaryTree();
    		}
    
    		return temp;
    	}
    	//  前序遍历
    	public void PreTree(Node t)
    	{
    		if(t == null)
    			return;
    		System.out.print(t.data + " ");
    		PreTree(t.leftChild);
    		PreTree(t.rightChild);
    	}
    
    	//  中序遍历
    	public void InOrderTree(Node t)
    	{
    		if(t == null)
    			return;
    		InOrderTree(t.leftChild);
    		System.out.print(t.data + " ");
    		InOrderTree(t.rightChild);
    	}
    
    	//  后序遍历
    	public void PostOrderTree(Node t)
    	{
    		if(t == null)
    			return;
    		PostOrderTree(t.leftChild);
    		PostOrderTree(t.rightChild);
    		System.out.print(t.data + " ");
    	}
    }
    

  • 相关阅读:
    【Prince2科普】衡量绩效的六大要素
    项目组合管理、项目集管理、项目管理和组织级项目管理之间的关系
    javascript中关系运算符的整理
    javascript中数组的基础----length和元素的求和
    回调函数和递归函数的应用
    谷歌浏览器打开时显示的是搜狗
    二级导航栏的立体显示
    利用css写的中英文切换的导航栏菜单
    javascript中的对象浅谈
    javascript中逻辑运算符总结
  • 原文地址:https://www.cnblogs.com/dengshiwei/p/4258469.html
Copyright © 2020-2023  润新知