zoukankan      html  css  js  c++  java
  • 105. 从前序与中序遍历序列构造二叉树-中等难度

    问题描述

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

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

    例如,给出

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

    3
    /
    9 20
    /
    15 7

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal

    解答

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int find(int[] a,int key){
            boolean flag = false;
            int index = 0;
            for(index=0;index<a.length;index++){
                if(a[index]==key){
                    flag = true;
                    break;
                }
            }
            if(flag)return index;
            return -1;
        }
        public TreeNode recursive(int[] pre, int[] in){
            if(in.length==0)return null;
            if(in.length==1)return new TreeNode(in[0],null,null);
            TreeNode r = null;
            int position = find(in,pre[0]);
            TreeNode l = recursive(Arrays.copyOfRange(pre, 1, position+1),Arrays.copyOfRange(in, 0, position));
            if(position+1<in.length)
            r = recursive(Arrays.copyOfRange(pre, position+1, pre.length),Arrays.copyOfRange(in, position+1, in.length));
            return new TreeNode(pre[0],l,r);
        }
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            if(preorder.length==0)return null;
            return recursive(preorder,inorder);
        }
    }
  • 相关阅读:
    人一生要去的100个地方(世界)
    数据仓库相关书籍
    学理财要看的书籍
    数仓设计 Building the Data Warehouse
    Google Cloud 安装java
    Google Cloud install python3 (in CentOS)
    SyntaxError: Non-ASCII character 'xe5' in file test23.py on line 2, but no encoding declared;
    CentOS 安装7z
    CentOS 安装 MySQL
    复杂迭代代码分析
  • 原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/13286876.html
Copyright © 2011-2022 走看看