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

本文共 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://bdrsl.baihongyu.com/

你可能感兴趣的文章
CSS技巧(二)
查看>>
MATLAB数值计算与数据分析(4)
查看>>
HDU 2079 选课时间(题目已修改,注意读题)(简单的母函数运用)
查看>>
NYOJ260数数小木块
查看>>
云中漫步 - 1:申请 Azure 账号
查看>>
oralce health monitor
查看>>
SqlHelper
查看>>
前端画面-下拉后滚动
查看>>
golang使用http client发起get和post请求示例
查看>>
pathway 中几张特殊的通路图
查看>>
Java基础之深入理解Class对象与反射机制
查看>>
remoting生命周期
查看>>
javascript 复制功能 兼容所有浏览器的解决方案
查看>>
粒子滤波实现物体跟踪
查看>>
关于gcc、glibc和binutils模块之间的关系
查看>>
C#窗体内嵌外部程序(cmd.exe)的显示 转
查看>>
解决js跨域问题
查看>>
POJ 计算几何(2)
查看>>
【本科毕业设计论文】分布式网络爬虫的研究与实现
查看>>
12、浅谈MySQL主键
查看>>