• 完美二叉树


    不废话,直接上代码

    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();
    	}
    }
    


  • 相关阅读:
    LeetCode 4 :Majority Element
    LeetCode 3 :Min Stack
    Oracle操作4
    plsql安装教程
    java Date与String互相转化
    Oracle操作3
    Oracle操作2
    Oracle操作
    Oracle11g修改密码
    Visual Studio2013完全卸载
  • 原文地址:https://www.cnblogs.com/suncoolcat/p/3325038.html
Copyright © 2020-2023  润新知