zoukankan      html  css  js  c++  java
  • 前序遍历和中序遍历树构造二叉树

    样例

    给出中序遍历:[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;
        }
    }





  • 相关阅读:
    [原创] Python3.6+request+beautiful 半次元Top100 爬虫实战,将小姐姐的cos美图获得
    手算平方根和基于 Java BigInteger 的大整数平方根的实现
    Spyder项目创建,打开与使用
    手动实现自己的spring事务注解
    springboot2.x配置druid sql监控
    基于zookeeper实现分布式锁
    数据库中间件之mycat读写分离
    springboot + shiro 构建权限模块
    数据库中间件之mycat安装部署(一)
    使用jdk8 stream简化集合操作
  • 原文地址:https://www.cnblogs.com/yanernanfei/p/7636226.html
Copyright © 2011-2022 走看看