剑指offer7重建二叉树

97 阅读1分钟

🍀重建二叉树

描述:

 # 输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
 
 示例 1:
 Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
 Output: [3,9,20,null,null,15,7]
 
 示例 2:
 Input: preorder = [-1], inorder = [-1]
 Output: [-1]
  
 
 限制:
 0 <= 节点个数 <= 5000

思考:

这个题需要一点二叉树知识,了解先根遍历和中根遍历能唯一确定一个二叉树,剩下的就是把方法变为代码的过程了,这个方法是确定一个先根遍历的根节点,然后再从中根遍历中找到这个节点,找到就赋值给创建的新节点,找不到就是null。

实现:

 class Solution {
     public TreeNode buildTree(int[] preorder, int[] inorder) {
         int len = preorder.length;
         if (len == 0) {
             return null;
         }
         int rootVal = preorder[0], rootIndex = 0;
         for (int i = 0; i < len; i++) {
             if (inorder[i] == rootVal) {
                 rootIndex = i;
                 break;
             }
         }
         TreeNode root = new TreeNode(rootVal);
         root.left = buildTree(Arrays.copyOfRange(preorder, 1, 1 + rootIndex), Arrays.copyOfRange(inorder, 0, rootIndex));
         root.right = buildTree(Arrays.copyOfRange(preorder, 1 + rootIndex, len), Arrays.copyOfRange(inorder, rootIndex + 1, len));
 ​
         return root;
     }
 }

效率低得可怜,不过递归很好理解,这个递归参考了一个大佬的写法。