zoukankan      html  css  js  c++  java
  • 105 Construct Binary Tree from Preorder and Inorder Traversal 从前序与中序遍历序列构造二叉树

    给定一棵树的前序遍历与中序遍历,依据此构造二叉树。
    注意:
    你可以假设树中没有重复的元素。
    例如,给出
    前序遍历 = [3,9,20,15,7]
    中序遍历 = [9,3,15,20,7]
    返回如下的二叉树:
        3
       /
      9  20
        / 
       15   7
    详见:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/

    Java实现:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public TreeNode buildTree(int[] pre, int[] in) {
            if(pre==null||pre.length==0||in==null||in.length==0||pre.length!=in.length){
                return null;
            }
            return reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);
        }
        private TreeNode reConstructBinaryTree(int[] pre,int startPre,int endPre,int[] in,int startIn,int endIn){
            if(startPre>endPre||startIn>endIn){
                return null;
            }
            TreeNode tree=new TreeNode(pre[startPre]);
            for(int i=startIn;i<=endIn;++i){
                if(in[i]==pre[startPre]){
                    tree.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);
                    tree.right=reConstructBinaryTree(pre,startPre+i-startIn+1,endPre,in,i+1,endIn);
                }
            }
            return tree;
        }
    }
    
  • 相关阅读:
    Maven属性
    安居客Android项目架构演进
    HttpClient 解说 (1) 基础
    linux 打包和压缩文件
    java AES-256加解密解决方法
    jdk8 分隔字符串最新方法
    springboot 过滤器,拦截器,切片的运用
    thinkphp 5.0手记
    如何使用UDP进行跨网段广播
    php multicast多播实现详解
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8719081.html
Copyright © 2011-2022 走看看