package com.qf.homework;
public class Demo1 {
public static void main(String[] args) {
String str = "java,python,iOS,bigdata,html,javascript,php,UI,goodgoodstudy,c,go,linkedHash,Set,TreeMap";
TreeNode p = new TreeNode("1",new TreeNode("2",new TreeNode("3"),new TreeNode("4")),new TreeNode("5"));
//precious(p);
// inOrder(p);
// after(p);
TreeNode root = getTreeNode(str);
precious(root);
}
public static TreeNode getTreeNode(String str){
String[] words = str.split(",");
TreeNode root = new TreeNode(words[0]);
for (int i = 0; i < words.length; i++) {
createBST(root,words[i]);
}
return root;
}
private static void createBST(TreeNode root, String word) {
if (word.length() < root.val.length()){
if (root.left == null) root.left = new TreeNode(word);
else createBST(root.left,word);
}else {
if (root.right == null) root.right = new TreeNode(word);
else createBST(root.right,word);
}
}
//先序
public static void precious(TreeNode root){
if (root == null) return;
if (root != null){
System.out.println(root.val);
precious(root.left);
precious(root.right);
}
}
//中序
public static void inOrder(TreeNode root){
if (root == null) return;
inOrder(root.left);
System.out.println(root.val);
inOrder(root.right);
}
//后序
public static void after(TreeNode root) {
if (root == null) return;
after(root.left);
after(root.right);
System.out.println(root.val);
}
}
class TreeNode{
String val;
TreeNode left;
TreeNode right;
public TreeNode() {
}
public TreeNode(String val) {
this.val = val;
}
public TreeNode(String val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
@Override
public String toString() {
return "TreeNode{" +
"val=" + val +
", left=" + left +
", right=" + right +
'}';
}
}
谢谢观看!