博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
105. Construct Binary Tree from Preorder and Inorder Traversal
阅读量:7041 次
发布时间:2019-06-28

本文共 1567 字,大约阅读时间需要 5 分钟。

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

Note:
You may assume that duplicates do not exist in the tree.
For example, given

preorder = [3,9,20,15,7]inorder = [9,3,15,20,7]Return the following binary tree:    3   / \  9  20    /  \   15   7

难度:Medium

题目: 给定二叉树的前序和中序遍历,构造二叉树,注意:二叉树结点值不重复。

思路:分治,

  1. 在前序中找出根结点r,
  2. 再在中序中找出r的位置,以该结点一分为二,继续执行1

Runtime: 8 ms, faster than 57.64% of Java online submissions for Construct Binary Tree from Preorder and Inorder Traversal.

Memory Usage: 37.5 MB, less than 49.23% of Java online submissions for 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 TreeNode buildTree(int[] preorder, int[] inorder) {        if (null == preorder || preorder.length < 1) {            return null;        }                return buildTree(preorder, 0, inorder, 0, inorder.length - 1);    }        private TreeNode buildTree(int[] preorder, int idx, int[] inorder, int s, int e) {        if (s > e) {            return null;        }        TreeNode root = new TreeNode(preorder[idx]);        int rIdx = s;        for (; rIdx <= e; rIdx++) {            if (inorder[rIdx] == preorder[idx]) {                break;            }        }        root.left = buildTree(preorder, idx + 1, inorder, s, rIdx - 1);        root.right = buildTree(preorder, idx + rIdx - s + 1, inorder, rIdx + 1, e);                return root;    }}

转载地址:http://xvhal.baihongyu.com/

你可能感兴趣的文章
DIY物联网应用 3-控制继电器
查看>>
MaxCompute基础与MaxCompute SQL优化
查看>>
CentOS下软链接建立与删除
查看>>
使用阿里云容器服务Jenkins 2.0实现持续集成之Pipeline篇(updated on 2016.12.23)
查看>>
Redis---持久化 ( RDB AOF )
查看>>
Introducing mcrouter: A memcached protocol router for scaling memcached deployments
查看>>
码栈开发手册(四)---编码方式开发(其他功能函数)
查看>>
android动画之interpolator和typeEvaluator用法详解
查看>>
排序算法之Bogo排序
查看>>
Speed up your Internet browsing on Linux with a DNS Cache server
查看>>
我的失败与伟大 —— 合作伙伴的甄别
查看>>
APP运营中必须关注的7大数据指标
查看>>
kettle数据同步的五种方案
查看>>
如何用IE的开发人员工具选择Iframe里面的元素
查看>>
linux 常用命令(1) grep
查看>>
第三方开发的网贷系统安全如何保障
查看>>
Java千百问_05面向对象(006)_is-a,has-a,like-a是什么
查看>>
Android SDK r20.x更新时,没有Android API的问题
查看>>
PHPWind发布新产品架构图
查看>>
GitHub学习笔记
查看>>