以#为终止符构建先序二叉树
eg. 12#4#5##3##
public int index = 0;
public TreeNode constructPreorderTree(char[] str){
if(str[index++] == '#') return null;
TreeNode node = new TreeNode(str[index]-'0');
index++;
node.left = constructPreorderTree(str);
node.right = constructPreorderTree(str);
return node;
}
以#为终止符构建中序二叉树
eg. #2#4#5#1#3#
public int index = 0;
public TreeNode constructInorderTree(char[] str){
if(str[index++] == '#') return null;
TreeNode left = constructInorderTree(str);
TreeNode node = new TreeNode(str[index]-'0');
node.left = left;
index++;
node.right = constructInorderTree(str);
return node;
}
以#为终止符构建后序二叉树
eg. ####542##31
public int index = 0;
public TreeNode constructPostorderTree(char[] str){
if(str[index++] == '#') return null;
TreeNode left = constructPostorderTree(str);
TreeNode right = constructPostorderTree(str);
TreeNode node = new TreeNode(str[index]-'0');
node.left = left;
node.right = right;
index++;
return node;
}
给先序中序重构二叉树
12453
24513
思路:每次遍历先序找到根,根据找到的根和中序遍历序列可以将树分成两半了。不断递归。
int preIter = 0;
public TreeNode constructFromPreAndIn(int[] pre, int[] in){
return construct(pre, in, 0, in.length-1);
}
public TreeNode construct(int[] pre, int[] in, int start, int end){
if(start > end) return null;
int val = pre[preIter++];
TreeNode root = new TreeNode(val);
int i = start;
for(; i <= end && in[i] != val; i++);
root.left = construct(pre, in, start, i-1);
root.right = construct(pre, in, i+1, end);
return root;
}
给后序中序重构二叉树
int postIter;
public TreeNode constructFromPreAndIn(int[] in, int[] post){
postIter = post.length-1;
return construct(post, in, 0, in.length-1);
}
public TreeNode construct(int[] post, int[] in, int start, int end){
if(start > end) return null;
int val = post[postIter--];
TreeNode root = new TreeNode(val);
int i = start;
for(; i <= end && in[i] != val; i++);
root.right = construct(post, in, i+1, end);
root.left = construct(post, in, start, i-1);
return root;
}