package tree.test;
import java.util.LinkedList;
import tree.domian.TreeNode;
public class Test {
public static void main(String[] args) {
String hx = "KBFDCAE";
print(tree);
}
private static TreeNode createTreeNode(String hx, String zx) {
TreeNode node = new TreeNode();
int size = hx.length();
String c = hx.charAt(size-1)+"";
node.setLeftChild(createTreeNode(hx.substring(0, index),zx.substring(0, index)));
node.setRightChild(createTreeNode(hx.substring(index,size-1),zx.substring(index+1)));
}
private static void print(TreeNode tree) {
if(tree==null){
System.out.println("null");
return;
}
LinkedList<TreeNode> list = new LinkedList<TreeNode>();
list.add(tree);
while(list.size()>0){
TreeNode temp = list.removeLast();
String data = temp.getData();
System.out.println(data+" ");
TreeNode left = temp.getLeftChild();
TreeNode right = temp.getRightChild();
if(left!=null)
list.addFirst(left);
if(right!=null)
list.addFirst(right);
}
}
private static void toTree(TreeNode tree, String hx, String zx) {
int size = hx.length();
String c = hx.charAt(size-1)+"";
tree.setData(c);
if(size==1)
return;
int index = zx.indexOf(c);
if(index>0){
tree.setLeftChild(new TreeNode());
toTree(tree.getLeftChild(),hx.substring(0, index),zx.substring(0, index));
}
if(index<size-1){
tree.setRightChild(new TreeNode());
toTree(tree.getRightChild(),hx.substring(index,size-1),zx.substring(index+1));
}
}
}
import java.util.LinkedList;
import tree.domian.TreeNode;
public class Test {
public static void main(String[] args) {
String hx = "KBFDCAE";
String zx = "BKFEACD";
方法一
// toTree(tree,hx,zx);
方法二
print(tree);
}
private static TreeNode createTreeNode(String hx, String zx) {
TreeNode node = new TreeNode();
int size = hx.length();
String c = hx.charAt(size-1)+"";
node.setData(c);
//如果size为1说明它已经到最后一个没有左右孩子直接返回
return node;
//获取后序最后的数即根节点查找在中序中出现的索引的位置
int index = zx.indexOf(c);
//如果index>0说明它有左孩子
node.setLeftChild(createTreeNode(hx.substring(0, index),zx.substring(0, index)));
}
//如果index<size-1说明它有右孩子
node.setRightChild(createTreeNode(hx.substring(index,size-1),zx.substring(index+1)));
}
//返回添加孩子后的节点
}
private static void print(TreeNode tree) {
if(tree==null){
System.out.println("null");
return;
}
LinkedList<TreeNode> list = new LinkedList<TreeNode>();
list.add(tree);
while(list.size()>0){
TreeNode temp = list.removeLast();
String data = temp.getData();
System.out.println(data+" ");
TreeNode left = temp.getLeftChild();
TreeNode right = temp.getRightChild();
if(left!=null)
list.addFirst(left);
if(right!=null)
list.addFirst(right);
}
}
private static void toTree(TreeNode tree, String hx, String zx) {
int size = hx.length();
String c = hx.charAt(size-1)+"";
tree.setData(c);
if(size==1)
return;
int index = zx.indexOf(c);
if(index>0){
tree.setLeftChild(new TreeNode());
toTree(tree.getLeftChild(),hx.substring(0, index),zx.substring(0, index));
}
if(index<size-1){
tree.setRightChild(new TreeNode());
toTree(tree.getRightChild(),hx.substring(index,size-1),zx.substring(index+1));
}
}
}