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);
        }
    }
  • 相关阅读:
    HDU 5528 Count a * b 欧拉函数
    HDU 5534 Partial Tree 完全背包
    HDU 5536 Chip Factory Trie
    HDU 5510 Bazinga KMP
    HDU 4821 String 字符串哈希
    HDU 4814 Golden Radio Base 模拟
    LA 6538 Dinner Coming Soon DP
    HDU 4781 Assignment For Princess 构造
    LA 7056 Colorful Toy Polya定理
    LA 6540 Fibonacci Tree
  • 原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/13286876.html
Copyright © 2011-2022 走看看