题目:假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。牛客网剑指offer4
该题的大体思路如下
通过图我们可以了解到我们需要不断通过先序遍历获取头节点,根据中序遍历获取其左右子树,每次获取的头节点下都有一棵树,根据此特性可知这是一个递归的思路。代码如下:
import java.util.*;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if (pre.length == 0) {
return null;
}
int rootVal = pre[0];
TreeNode root = new TreeNode(rootVal);
int leftCount = 0;
for (int i = 0; i < in.length; i++) {
if (in[i] == rootVal) {
leftCount = i;
break;
}
}
int[] leftPre = Arrays.copyOfRange(pre, 1, 1 + leftCount);
int[] leftIn = Arrays.copyOfRange(in, 0, leftCount);
TreeNode left = reConstructBinaryTree(leftPre, leftIn);
root.left = left;
int[] rightPre = Arrays.copyOfRange(pre, 1 + leftCount, pre.length);
int[] rightIn = Arrays.copyOfRange(in, 1 + leftCount, in.length);
TreeNode right = reConstructBinaryTree(rightPre, rightIn);
root.right = right;
return root;
}
}
:-D:)
发布了35 篇原创文章 · 获赞 4 · 访问量 1195
私信
关注