zoukankan      html  css  js  c++  java
  • 完美二叉树

    不废话,直接上代码

    class BinaryTree { // 定义二叉树的操作类
    	class Node {
    		private Comparable data; // 保存数据
    		private Node left;// 表示左子树
    		private Node right;// 表示右子树
    		public Node(Comparable data) {
    			this.data = data;
    		}
    		public void addNode(Node newNode) {
    			if (((Integer)(newNode.data)).compareTo((Integer)(this.data)) < 0) {
    				if (this.left == null) { // 当前的左子树是否等于空
    					this.left = newNode;
    				} else {
    					this.left.addNode(newNode);// 继续向下继续判断
    				}
    			}
    			if (((Integer)(newNode.data)).compareTo((Integer)(this.data)) >= 0) {
    				if (this.right == null) { // 当前的右子树是否等于空
    					this.right = newNode;
    				} else {
    					this.right.addNode(newNode);
    				}
    			}
    		}
    		public void printNode() {
    			if (this.left != null) {
    				this.left.printNode();
    			}
    			System.out.println(this.data);
    			if (this.right != null) {
    				this.right.printNode();
    			}
    		}
    	}
    	private Node root; // 定义根节点
    	public void add(Comparable data) { // 表示增加节点
    		Node newNode = new Node(data);
    		if (this.root == null) { // 此时没有根节点,第一个元素作为根节点
    			this.root = newNode;
    		} else { // 判断节点是放在左子树还是右子树
    			this.root.addNode(newNode);
    		}
    	}
    	public void print() { // 打印节点
    		this.root.printNode();
    	}
    }
    
    
    public class BinaryTreeDemo {
    	public static void main(String[] args) {
    		BinaryTree bt = new BinaryTree();
    		bt.add(5);
    		bt.add(3);
    		bt.add(1);
    		bt.add(90);
    		bt.add(90);
    		bt.add(100);
    		bt.add(60);
    		bt.print();
    	}
    }
    


  • 相关阅读:
    BZOJ2809 dispatching
    BZOJ1486 最小圈
    BZOJ1096 仓库建设
    BZOJ3190 赛车
    BZOJ1911 特别行动队
    BZOJ1202 狡猾的商人
    BZOJ1007 水平可见直线
    BZOJ2150 部落战争
    如何用PHP遍历文件数目 或删除目录下的全部文件?
    php对文件/目录操作的基础知识(图解)
  • 原文地址:https://www.cnblogs.com/suncoolcat/p/3325038.html
Copyright © 2011-2022 走看看