二叉树的重建问题dfs:
力扣105、106(从遍历中构建二叉树)、654最大二叉树、617合并二叉树
1.从前序和中序遍历中构建二叉树
注意这个边界条件,当inStart>inEnd的时候返回null,当inStart==inEnd的时候,说明到达了叶子节点,返回构造节点即可。
private TreeNode rebuild(int[]preorder,int preStart,int preEnd,int[] inorder,int inStart,int inEnd){
if(inStart>inEnd){
return null;
}
if(inStart==inEnd){
return new TreeNode(inorder[inStart]);
}
TreeNode root = new TreeNode(preorder[preStart]);
int inRootIndex=0;
while (inorder[inRootIndex]!=root.val){
inRootIndex++;
}
int leftCount=inRootIndex-inStart;
root.left=rebuild(preorder, preStart+1, preStart+leftCount, inorder, inStart, inRootIndex-1);
root.right=rebuild(preorder, preStart+leftCount+1, preEnd, inorder, inRootIndex+1, inEnd);
return root;
2.从中序和后序遍历中构建二叉树
private TreeNode rebuilder(int[]inorder,int inStart,int inEnd,int[]postorder,int postStart,int postEnd){
if(inStart>inEnd){
return null;
}
if(inStart==inEnd){
return new TreeNode(inorder[inStart]);
}
TreeNode root = new TreeNode(postorder[postEnd]);
int inRootIndex=0;
while (inorder[inRootIndex]!=root.val){
inRootIndex++;
}
int leftCount=inRootIndex-inStart;
root.left=rebuilder(inorder, inStart, inRootIndex-1, postorder, postStart, postStart+leftCount-1);
root.right=rebuilder(inorder, inRootIndex+1, inEnd, postorder, postStart+leftCount, postEnd-1);
return root;
}
3.最大二叉树
private TreeNode rebuilder(int[]nums,int start,int end){
if(start>end){
return null;
}
if(start==end){
return new TreeNode(nums[start]);
}
int maxIndex=start;
int maxValue=nums[start];
int temp=start;
while (temp<=end){
if(nums[temp]>maxValue){
maxValue=nums[temp];
maxIndex=temp;
}
temp++;
}
TreeNode root = new TreeNode(maxValue);
root.left=rebuilder(nums,start,maxIndex-1);
root.right=rebuilder(nums,maxIndex+1,end);
return root;
}
4.合并二叉树
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if(root1==null&&root2==null){
return null;
}else if(root1!=null&&root2==null){
return root1;
}else if(root1==null&&root2!=null){
return root2;
}
TreeNode root = new TreeNode(root1.val + root2.val);
root.left=mergeTrees(root1.left,root2.left);
root.right=mergeTrees(root1.right,root2.right);
return root;
}