剑指offer:重建二叉树(递归,LeetCode105 从前序与中序遍历序列构造二叉树)

题目:

根据一棵树的前序遍历与中序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

答案:

解法一:

递归的方法计算根节点的左右子树,代码如下:

注意Arrays.copyOfRange函数是左闭右开的。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
public class Solution {
        public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if(pre==null||in==null||pre.length==0||in.length==0){
            return null;
        }
        TreeNode root = new TreeNode(pre[0]);
        if(pre.length==1){
            return root;
        }
        int root_index = arrayIndexOf(in,pre[0]);
        root.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,1+root_index),Arrays.copyOfRange(in,0,root_index));
        root.right = reConstructBinaryTree(Arrays.copyOfRange(pre,root_index+1,pre.length),Arrays.copyOfRange(in,root_index+1,in.length));
        
        return root;
    }
    
    public static int arrayIndexOf(int[] array,int target){
        for(int i=0;i<array.length;i++){
            if(array[i]==target){
                return i;
            }
        }
        return -1;
    }
}

解法二:

https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/solution/cong-qian-xu-he-zhong-xu-bian-li-xu-lie-gou-zao-er

发布了75 篇原创文章 · 获赞 2 · 访问量 7999

猜你喜欢

转载自blog.csdn.net/wyplj2015/article/details/104829427
今日推荐