剑指offer(牛客网)-第四题-重构二叉树
题目
输入某二叉树的前序遍历和中序遍历的结果,请重构出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如:
输入前序遍历序列[1,2,4,7,2,5,6,8]
输入中序遍历序列[4,7,2,1,5,3,8,6]
解析
- 前序遍历的顺序是,根左右,所以第一个数字总是树的根节点
- 中序遍历的顺序是,左根右,所以根节点在序列的中间,根节点左边为左子树,右边为右子树
- 综上所述,我们可以使用递归去完成左右子树的构造。
代码
public class solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
TreeNode root = reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
return root;
}
private TreeNode reConstructBinaryTree(int [] pre, int startPre, int endPre, int [] in, int startIn, int endIn) {
if (startPre > endPre || startIn > endIn) {
return null;
}
// 根节点总是为前序遍历序列的第一个节点
TreeNode root = new TreeNode(pre[startPre]);
for(int i = startIn; i <= endIn; i++) {
if (pre[startPre] == in[i]) {
// 构造左右子树
root.left = reConstructBinaryTree(pre, startPre + 1, i - startIn + startPre, in, startIn, i - 1);
root.right = reConstructBinaryTree(pre, i - startIn + startPre + 1, endPre, in, i + 1, endIn);
// 当找到了根节点之后,就要跳出循环
break;
}
}
return root;
}
}
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode (int x) {
this.val = x;
}
}
来源:CSDN
作者:向阳的葵花饼
链接:https://blog.csdn.net/weixin_44419313/article/details/103652845