标签:中序遍历 rgs 递归 treenode 位置 代码 ons 判断 如何
给你前序遍历中序遍历,如何构造出一个二叉树?
思路:
1. 明确前序遍历与中序遍历的顺序
前序遍历:根→左子树→右子树
中序遍历:左子树→根→右子树
2. 根据前序遍历可确认根节点,在中序遍历中根节点是一个分水岭,可由根节点分辨出左右子树
3. 对左右子树分别重复第2步,可以找出左右子树的子树,也就是递归操作
代码:
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
public static TreeNode reConstructBinaryTree(int [] pre,int [] in) {
//1.由前序遍历确认根节点
int node=pre[0];
TreeNode tree=new TreeNode(node);
//2.由中序遍历确认左右子树节点
ArrayList<Integer> leftTreeForIn=new ArrayList<>();
ArrayList<Integer> rightTreeForIn=new ArrayList<>();
int nodePosition=-1;
for(int i=0;i<in.length;i++){
if(in[i]==node){
nodePosition=i; //确认根节点在中序遍历中的位置
}
//根据根节点将左右子树的节点分别放入两个list中
if(nodePosition<0){
leftTreeForIn.add(in[i]);
}else if(nodePosition>=0 && nodePosition<i){
rightTreeForIn.add(in[i]);
}
}
//3.为树添加左右子树
if(leftTreeForIn.size()>0){
TreeNode left;
if(leftTreeForIn.size()==1){ //判断左子树是否有叶子节点,左子树只有1个节点则表示无叶子节点
left=new TreeNode(leftTreeForIn.get(0));
}else{ //有叶子节点则进行递归操作
int[] leftTreeForPre=new int[leftTreeForIn.size()];
for(int i=0;i<leftTreeForIn.size();i++){
leftTreeForPre[i]=pre[i+1];
}
left=reConstructBinaryTree(leftTreeForPre,Arrays.stream(leftTreeForIn.toArray(new Integer[]{})).mapToInt(Integer::valueOf).toArray());
}
tree.left=left;
}
if(rightTreeForIn.size()>0){
TreeNode right;
if(rightTreeForIn.size()==1){
right=new TreeNode(rightTreeForIn.get(0));
}else{
int[] rightTreeForPre=new int[rightTreeForIn.size()];
for(int i=0;i<rightTreeForIn.size();i++){
rightTreeForPre[i]=pre[i+1+leftTreeForIn.size()];
}
right=reConstructBinaryTree(rightTreeForPre,Arrays.stream(rightTreeForIn.toArray(new Integer[]{})).mapToInt(Integer::valueOf).toArray());
}
tree.right=right;
}
return tree;
}
public static void main(String[] args){
int[] pre={1,2,4,7,3,5,6,8};
int[] in={4,7,2,1,5,3,8,6};
TreeNode tree=reConstructBinaryTree(pre,in);
System.out.println(tree.left.left.right.val);
}
}
标签:中序遍历 rgs 递归 treenode 位置 代码 ons 判断 如何
原文地址:https://www.cnblogs.com/zhangrr/p/10620915.html