中后序建树
今晚熬夜撸一篇算法(不然睡觉都不踏实!哈哈哈)*
话不多说!!上代码!!!
(我解释很详细了哈,有不懂的,欢迎评论区留言,一起讨论,一起成长!!!
)
题目要求:
根据一棵树的中序遍历
与后序遍历
构造二叉树
。
注意:
此情况是假设树中没有重复
的元素。
public class 中后序建立二叉树 {
/**
* 利用下标索引法
*/
public TreeNode traversal(int[] inorder,int in_start,int in_end,int[] postorder,int post_start,int post_end){
//1.判断是否为空
if(post_end==post_start) return null;
//2.获取后续遍历的最后一个节点(根节点)
int rootval=postorder[post_end-1];
//3.建树
TreeNode root=new TreeNode(rootval);
//4.判断后续遍历的数组是否只有普最后一个数组了(叶子结点)
if(post_end-post_start==1) return root;
//5.建立切割垫
int split_dot;
for(split_dot=in_start;split_dot<in_end;split_dot++){
if(inorder[split_dot]==rootval){
break;
}
}
//6.切割中序数组
//左中序区间,左闭右开
int l_instart=in_start;
int l_inend=split_dot;
//右中序区间
int r_instart=split_dot+1;
int r_inend=in_end;
//7.切割后续数组
//左后序区间
int l_poststart=post_start;
int l_postend=post_start+split_dot-in_start;//终止位置(就是左中序数组的长度)
//右后序区间
int r_poststart=post_start+(split_dot-in_start);
int r_postend=post_end-1;//建议的操作是为了排除最后一个元素
//8.将余下的数遍历组装进左右树
root.left=traversal(inorder,l_instart,l_inend,postorder,l_poststart,l_postend);
root.right=traversal(inorder,r_instart,r_inend,postorder,r_poststart,r_postend);
return root;
}
}
不能完结撒花
前中遍历代码后续补录上