总结:这周主要是按照计划来进行,然后在算法中也是遇到了自己不是很熟悉的知识点,这道算法
自己也去查了很多 ,看一下:
重建二叉树:
1.输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。(没有重复的数字)
2.假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列                {1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
   | /**  * Definition for binary tree  * public class TreeNode {  *     int val;  *     TreeNode left;  *     TreeNode right;  *     TreeNode(int x) { val = x; }  * }  */
  public class Solution {
      // 被调用函数     public TreeNode reConstructTree(int [] pre, int prestart, int preend,int [] in, int instart, int inend){
          if(prestart > preend || instart > inend) {             return null;         }
          // 构建根节点         int rootvalue = pre[prestart];         TreeNode root = new TreeNode(rootvalue);
 
          // for循环找到中序数组中的根节点下标,以此下标减去 中序数组 首节点下标, 得到中序数组中 左子树的size         int index = 0;         for(int i=instart; i<=in.length; i++) {             if(in[i] == root.val) {                 index = i;                 break;             }         }
          int leftsize = index - instart;
          // 分别递归构造根节点的左右子树         root.left = reConstructTree(pre, prestart+1, prestart+leftsize, in, instart, index-1);         root.right = reConstructTree(pre, prestart+leftsize+1, preend, in, index+1, inend);
          return root;     }
 
      //函数入口, 传入一个 前序数组 和 一个中序数组     public TreeNode reConstructBinaryTree(int [] pre,int [] in) {         if(pre == null || in == null)             return null;
 
          return reConstructTree(pre, 0, pre.length-1, in, 0, in.length-1);     } }
   | 
 
比较难理解的点:
1.边界条件的考虑;
在索引数组最后一个节点的时候,需要注意length指的是数组的长度,而 pre.length 已经超过了数组的索引长度,所以我们在函数的入口处直接将  pre.length-1 / in.length -1 作为最后一个节点的下标;
2.分别递归构造左右子树的时候, 标注红色部分的区别容易搞错。
root.left = reConstructTree(pre, prestart+1, prestart+leftsize, in, instart, index-1);
        root.right = reConstructTree(pre, prestart+leftsize+1, preend, in, index+1, inend);
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 fortunate!