剑指 Offer 07. 重建二叉树

1. 题目

输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

2. 示例

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]

二叉树:

    3
   / 
  9  20
    /  
   15   7

3. 题解

本题很明显的递归套路。

但首先要了解三种遍历的顺序:

前序遍历:[根节点,左子树,右子树]

中序遍历:[左子树,根节点,右子树]

后序遍历:[左子树,右子树,根节点]

观察发现:前序遍历的左子树始终是第一位,然后中序遍历中将链表划分成左部分左子树,右部分右子树。

那么,我们秩序递归获取根节点,然后对左子树和右子树进行划分即可。

4. 实现

 1 public TreeNode buildTree(int[] preorder, int[] inorder) {
 2         int n = preorder.length;
 3         if (n == 0) return null;
 4         int rooVal = preorder[0], rootIndex = 0;
 5         for (int i = 0; i < n; i++) {
 6             if (inorder[i] == rooVal) {
 7                 rootIndex = i;
 8                 break;
 9             }
10         }
11         TreeNode root = new TreeNode(rooVal);
12         root.left = buildTree(Arrays.copyOfRange(preorder, 1, 1 + rootIndex), Arrays.copyOfRange(inorder, 0, rootIndex));
13         root.right = buildTree(Arrays.copyOfRange(preorder, 1 + rootIndex, n), Arrays.copyOfRange(inorder, rootIndex + 1, n));
14         return root;
15     }

5. 结语

  努力去爱周围的每一个人,付出,不一定有收获,但是不付出就一定没有收获! 给街头卖艺的人零钱,不和深夜还在摆摊的小贩讨价还价。愿我的博客对你有所帮助(*^▽^*)(*^▽^*)!

  如果客官喜欢小生的园子,记得关注小生哟,小生会持续更新(#^.^#)(#^.^#)。

但行好事 莫问前程
原文地址:https://www.cnblogs.com/haifwu/p/14952838.html