一、java方法
// 二叉树类
public class BinaryTree {
private Node root;
// 添加节点
public void add(int data) {
if(root == null) {
root = new Node(data);
}
else {
root.addNode(data);
}
}
// 打印整个二叉树
public void printTree() {
root.printNode();
}
// 内部类 Node
private class Node {
private int data;
private Node left;
private Node right;
public Node (data) {
this.data = data;
}
public void addNode(int data) {
if(this.data > data) {
if(this.left == null) {
this.left = new Node(data);
}
else {
this.left.addNode(data);
}
}
else {
if(this.right == null) {
this.right = new Node(data);
}
else {
this.right.addNode(data);
}
}
}
// 中序遍历的方法,左,中,右
public void printNode () {
if(this.left != null) {
this.left.printNode();
}
system.out.print(this.data + '->');
if(this.right != null) {
this.right.printNode();
}
}
}
}
// 测试类
public class Demo {
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
bt.add(8);
bt.add(1);
bt.add(4);
bt.add(23);
bt.add(3);
bt.add(-3);
bt.print();
}
}
二、js方法
class Nod1 {
constructor (data) {
this.value = data;
this.left = null;
this.right = null;
}
addInNode (data) {
if(this.value > data) {
if(this.left == null) {
this.left = new Nod1(data);
}
else {
this.left.addInNode(data);
}
}
else {
if(this.right == null) {
this.right = new Nod1(data);
}
else {
this.right.addInNode(data);
}
}
}
printNode () {
if(this.value != null) {
console.log(this.value);
this.left && this.left.printNode();
this.right && this.right.printNode();
}
}
}
class BinaryTre1 {
constructor () {
this.root = null;
}
addInTree (value) {
if(this.root == null) {
this.root = new Nod1(value);
}
else {
this.root.addInNode(value);
}
}
printTree () {
this.root.printNode();
}
}
var n1 = new Nod1(3);
var tree = new BinaryTre1(n1);
tree.addInTree(4);
tree.addInTree(1);
tree.addInTree(0);
tree.printTree();
网友评论