前序遍历和中序遍历树构造二叉树

样例

给出中序遍历:[1,2,3]和前序遍历:[2,1,3]. 返回如下的树

  2
 / 
1   3


思路:

1、根据前序遍历第一个节点值,创建根节点;

2、找到根节点在中序遍历中的位置i;

3、递归创建左右子树。

问题:第一次提交时方法 copyOfRange 误写成 copyofRange,提示cannot find symbol

import java.util.Arrays;
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
 

public class Solution {
    /**
     *@param preorder : A list of integers that preorder traversal of a tree
     *@param inorder : A list of integers that inorder traversal of a tree
     *@return : Root of a tree
     */
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        // write your code here
        if(inorder.length == 0){
            return null;
        }
        TreeNode r = new TreeNode(preorder[0]);
        int i = 0;
        while(i < inorder.length){
            if(inorder[i] == preorder[0]){
                break;
            }
            i ++;
        }
        if(i > 0){
            int [] pre = Arrays.copyOfRange(preorder,1,i+1);
            int [] in = Arrays.copyOfRange(inorder,0,i);
            r.left = buildTree(pre,in);
        }
        if(i < (inorder.length-1)){
            int [] pre = Arrays.copyOfRange(preorder,1+i,preorder.length);
            int [] in = Arrays.copyOfRange(inorder,i+1,inorder.length);
            r.right = buildTree(pre,in);
        }
        return r;
    }
}





原文地址:https://www.cnblogs.com/yanernanfei/p/7636226.html