105. 从前序与中序遍历序列构造二叉树
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
题解:
1)前/后+中 确定唯一的二叉树
2)前序遍历第一个元素为root
3)找到中序遍历中root,左边为左子树右边为右子树
4)递归
sloution:
简洁版:
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length==0||inorder.length==0){
return null;
}
TreeNode root=new TreeNode (preorder[0]);
for(int i=0;i<preorder.length;i++){
if(preorder[0]==inorder[i]){
root.left=buildTree(Arrays.copyOfRange(preorder,1,i+1),Arrays.copyOfRange(inorder,0,i));
root.right=buildTree(Arrays.copyOfRange(preorder,i+1,preorder.length),Arrays.copyOfRange(inorder,i+1,inorder.length));
break;
}
}
return root;
}
}
106. 从中序与后序遍历序列构造二叉树
根据一棵树的中序遍历与后序遍历构造二叉树。
注意:你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
题解:
1)前/后+中 确定唯一的二叉树
2)后续遍历最后一个元素为root
3)找到中序遍历中root,左边为左子树右边为右子树
4)递归
sloution:
同上 注意范围
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder.length==0||postorder.length==0){
return null;
}
TreeNode root=new TreeNode (postorder[postorder.length-1]);
for(int i=0;i<postorder.length;i++){
if(postorder[postorder.length-1]==inorder[i]){
root.left=buildTree(Arrays.copyOfRange(inorder,0,i),Arrays.copyOfRange(postorder,0,i));
root.right=buildTree(Arrays.copyOfRange(inorder,i+1,inorder.length),Arrays.copyOfRange(postorder,i,postorder.length-1));
break;
}
}
return root;
}
}
654. 最大二叉树
给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下:
二叉树的根是数组中的最大元素。
左子树是通过数组中最大值左边部分构造出的最大二叉树。
右子树是通过数组中最大值右边部分构造出的最大二叉树。
通过给定的数组构建最大二叉树,并且输出这个树的根节点。
题解:分治递归
sloution:
//官方
public class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return construct(nums, 0, nums.length);//返回最大二叉树的根节点
}
public TreeNode construct(int[] nums, int l, int r) {//创建construct方法
if (l == r) return null;
int max_i = max(nums, l, r);//找数组中最大数索引值max_i,对应作为根节点
TreeNode root = new TreeNode(nums[max_i]);
root.left = construct(nums, l, max_i);//左子树重复操作
root.right = construct(nums, max_i + 1, r);//右子树重复操作
return root;
}
public int max(int[] nums, int l, int r) {
int max_i = l;
for (int i = l; i < r; i++) {
if (nums[max_i] < nums[i])
max_i = i;
}
return max_i;
}
}