二叉树的重建问题dfs:
    力扣105、106(从遍历中构建二叉树)、654最大二叉树、617合并二叉树
    1.从前序和中序遍历中构建二叉树
    注意这个边界条件,当inStart>inEnd的时候返回null,当inStart==inEnd的时候,说明到达了叶子节点,返回构造节点即可。

    1. private TreeNode rebuild(int[]preorder,int preStart,int preEnd,int[] inorder,int inStart,int inEnd){
    2. if(inStart>inEnd){
    3. return null;
    4. }
    5. if(inStart==inEnd){
    6. return new TreeNode(inorder[inStart]);
    7. }
    8. TreeNode root = new TreeNode(preorder[preStart]);
    9. int inRootIndex=0;
    10. while (inorder[inRootIndex]!=root.val){
    11. inRootIndex++;
    12. }
    13. int leftCount=inRootIndex-inStart;
    14. root.left=rebuild(preorder, preStart+1, preStart+leftCount, inorder, inStart, inRootIndex-1);
    15. root.right=rebuild(preorder, preStart+leftCount+1, preEnd, inorder, inRootIndex+1, inEnd);
    16. return root;

    2.从中序和后序遍历中构建二叉树

    1. private TreeNode rebuilder(int[]inorder,int inStart,int inEnd,int[]postorder,int postStart,int postEnd){
    2. if(inStart>inEnd){
    3. return null;
    4. }
    5. if(inStart==inEnd){
    6. return new TreeNode(inorder[inStart]);
    7. }
    8. TreeNode root = new TreeNode(postorder[postEnd]);
    9. int inRootIndex=0;
    10. while (inorder[inRootIndex]!=root.val){
    11. inRootIndex++;
    12. }
    13. int leftCount=inRootIndex-inStart;
    14. root.left=rebuilder(inorder, inStart, inRootIndex-1, postorder, postStart, postStart+leftCount-1);
    15. root.right=rebuilder(inorder, inRootIndex+1, inEnd, postorder, postStart+leftCount, postEnd-1);
    16. return root;
    17. }

    3.最大二叉树

    1. private TreeNode rebuilder(int[]nums,int start,int end){
    2. if(start>end){
    3. return null;
    4. }
    5. if(start==end){
    6. return new TreeNode(nums[start]);
    7. }
    8. int maxIndex=start;
    9. int maxValue=nums[start];
    10. int temp=start;
    11. while (temp<=end){
    12. if(nums[temp]>maxValue){
    13. maxValue=nums[temp];
    14. maxIndex=temp;
    15. }
    16. temp++;
    17. }
    18. TreeNode root = new TreeNode(maxValue);
    19. root.left=rebuilder(nums,start,maxIndex-1);
    20. root.right=rebuilder(nums,maxIndex+1,end);
    21. return root;
    22. }

    4.合并二叉树

    1. public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
    2. if(root1==null&&root2==null){
    3. return null;
    4. }else if(root1!=null&&root2==null){
    5. return root1;
    6. }else if(root1==null&&root2!=null){
    7. return root2;
    8. }
    9. TreeNode root = new TreeNode(root1.val + root2.val);
    10. root.left=mergeTrees(root1.left,root2.left);
    11. root.right=mergeTrees(root1.right,root2.right);
    12. return root;
    13. }