[LeetCode][Java] Construct Binary Tree from Preorder and Inorder Traversal

来源:互联网 发布:大数据徐子沛百度云 编辑:程序博客网 时间:2024/06/05 16:31

题目:

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

题意:

给定一棵树的先序和中序遍历,构建这颗二叉树。

注意:

你可以假定这棵树中不存在重复。

算法分析:

  * 中序序列和后序序列构造二叉树和此题算法是一样的

  * 这里的区别是要从中序遍历和先序遍历中构造出树
   
  * 只是现在取根是从前面取(因为先序遍历根是遍历的第一个元素)。
   
  * 思想和代码基本都是差不多的,自然时间复杂度和空间复杂度也还是O(n)

AC代码:

<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution {    public TreeNode buildTree(int[] preorder, int[] inorder)     {        if(inorder==null || preorder==null || inorder.length==0 || preorder.length==0)            return null;                HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();        for(int i=0;i<inorder.length;i++)        {            map.put(inorder[i],i);        }        return helper(inorder,preorder,0,inorder.length-1, 0, preorder.length-1,map);    }    private TreeNode helper(int[] inorder, int[] preorder, int inL, int inR, int preL, int preR, HashMap<Integer, Integer> map)    {        if(inL>inR || preL>preR)            return null;        TreeNode root = new TreeNode(preorder[preL]);        int index = map.get(root.val);        root.left = helper(inorder,preorder,inL,index-1,preL+1,preR-(inR-index),map);        root.right = helper(inorder,preorder,index+1,inR,preL+index-inL+1,preR,map);        return root;    }}</span>


0 0
原创粉丝点击