-
二叉排序树代码
课上练习 有⼀组字符串 (java,python,iOS,bigdata,html,javascript,php,UI,goodgoodstudy,c,go,linkedHash Set,TreeMap) 要求:
1.按照⻓度顺序添加到⼆叉树中,⻓度相同按照字典排序
2.分别进⾏前序,中序,后序遍历
public class Tree {
public static void main(String[] args) {
String str = "java,python,iOS,bigdata,html,javascript,php,UI,goodgoodstudy,c,go,linkedHash,Set,TreeMap";
String[] split = str.split(",");
TreeNode head = init(split);
System.out.println(head.str);
middlePrint(head);
}
private static TreeNode init(String[] split) {
TreeNode treeNode = new TreeNode();
treeNode.str = split[0];
for (int i = 1; i < split.length; i++) {
TreeNode t = new TreeNode();
t.str = split[i];
addTreeNode(treeNode,t);
}
return treeNode;
}
private static void middlePrint(TreeNode treeNode) {
if(treeNode==null)
return;
middlePrint(treeNode.left);
System.out.print(treeNode.str+" ");
middlePrint(treeNode.right);
}
private static void addTreeNode(TreeNode treeNode, TreeNode t) {
if(treeNode==null)
return;
if(treeNode.compareTo(t)>0){
if(treeNode.left==null){
treeNode.left = t;
}else addTreeNode(treeNode.left,t);
}else {
if(treeNode.right==null){
treeNode.right = t;
}else addTreeNode(treeNode.right,t);
}
}