java 二叉树 分层排序_Java实现简单数据结构之二叉树结构排序 binary tree
package com.git.base.datastructure.binarytree;public class MyBinaryTree {private MyTreeNode root;publicvoid add(Comparable data){MyTreeNode node = new MyTreeNode();node.data = data;if(root ==null){r..
package com.git.base.datastructure.binarytree;
public class MyBinaryTree {
private MyTreeNode root;
public void add(Comparable data){
MyTreeNode node = new MyTreeNode();
node.data = data;
if(root ==null){
root =node;
}else{
root.addNode(node);
}
}
public void print(){
root.printNode();
}
class MyTreeNode{
private Comparable data;
private MyTreeNode left;
private MyTreeNode right;
public void addNode(MyTreeNode node){
if(node.data.compareTo(this.data)<0){// -1 代表当前的小于传入的
if(left ==null){
left = node;
}else{
left.addNode(node);
}
}else{
if(right ==null){
right =node;
}else{
right.addNode(node);
}
}
}
public void printNode(){//输出节点 从最小左边开始
if(this.left != null){//存在左节点就打印左节点
this.left.printNode();
}
System.out.println(this.data);//只有一个输出
if(this.right !=null){
this.right.printNode();
}
}
}
}
package com.git.base.datastructure.binarytree;
public class MyBinaryTreeDemo {
public static void main(String[] args) {
MyBinaryTree binaryTree = new MyBinaryTree();
binaryTree.add(7);
binaryTree.add(6);
binaryTree.add(8);
binaryTree.add(3);
binaryTree.add(9);
binaryTree.add(34);
binaryTree.add(8);
binaryTree.add(34);
binaryTree.add(7);
binaryTree.add(4);
binaryTree.print();
}
}
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)