Java 二叉树实现
二叉树是一种非线性结构
代码示例(Java实现二叉树)
package com.seven.javaSE; public class BinaryTreeDemo { private Node root; public void add(int data) { if(root==null) { root = new Node(data); } else { root.add(data); } } public void print() { if(root!=null) { root.print(); } } private class Node{ private Node left; private Node right; private int data; public Node(int data) { this.data = data; } //添加二叉树节点(左节点比父节点小,右节点大于等于父节点) public void add(int data) { if(this.data>data) { if(this.left==null) { this.left = new Node(data); } else { this.left.add(data); } } else { if(this.right==null) { this.right = new Node(data); } else { this.right.add(data); } } } //打印二叉树(中序遍历) public void print() { if(this.left!=null) { this.left.print(); } System.out.println(this.data); if(this.right!=null) { this.right.print(); } } } }
本文来自博客园,作者:藤原豆腐渣渣,转载请注明原文链接:https://www.cnblogs.com/javafufeng/p/16349069.html