题目描述:

  

方法一:

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
def helper(in_left=0,in_right=len(inorder)):
nonlocal pre_idx
# if there is no elements to construct subtrees
if in_left == in_right: return None
# pick up pre_idx element as a root
root_val = preorder[pre_idx]
root = TreeNode(root_val)
# root splits inorder list
# into left and right subtrees
index = idx_map[root_val]
# recursion
pre_idx += 1
# build left subtree
root.left = helper(in_left, index)
# build right subtree
root.right = helper(index + 1, in_right)
return root
# start from first preorder element
pre_idx = 0
# build a hashmap value -> its index
idx_map = {val:idx for idx, val in enumerate(inorder)}
return helper()

另:

class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
def helper(i,j):
while i<j:
root = TreeNode(preorder[0])
del preorder[0]
root.left = helper(i,idx_map[root.val])
root.right = helper(idx_map[root.val]+1,j)
return root
idx_map = {val:idx for idx, val in enumerate(inorder)}
return helper(0,len(inorder))

java版:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Map<Integer,Integer> dic = new HashMap<>();
int [] po;
public TreeNode buildTree(int[] preorder, int[] inorder) {
po = preorder;
for(int i = 0; i< inorder.length;i++)
dic.put(inorder[i],i);
return recur(0,0,inorder.length -1);
}
public TreeNode recur(int pre_root,int in_left,int in_right){
if(in_left > in_right) return null;
TreeNode root = new TreeNode(po[pre_root]);
int i = dic.get(po[pre_root]);
root.left = recur(pre_root + 1,in_left, i -1);
root.right = recur(pre_root + i - in_left + 1,i + 1,in_right);
return root;
}
}

迭代:java *

/**
* 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(preorder == null || preorder.length == 0){
return null;
}
TreeNode root = new TreeNode(preorder[0]);
int length = preorder.length;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
int inorderIndex = 0;
for (int i = 1; i < length; i++){
int preorderVal =preorder[i];
TreeNode node = stack.peek();
if (node.val != inorder[inorderIndex]) {
node.left = new TreeNode(preorderVal);
stack.push(node.left);
}else{
while(!stack.isEmpty() && stack.peek().val == inorder[inorderIndex]){
node = stack.pop();
inorderIndex++;
}
node.right = new TreeNode(preorderVal);
stack.push(node.right);
}
}
return root;
}
}

leetcode-105-从前序与中序遍历构造二叉树的更多相关文章

  1. Java实现 LeetCode 105 从前序与中序遍历序列构造二叉树

    105. 从前序与中序遍历序列构造二叉树 根据一棵树的前序遍历与中序遍历构造二叉树. 注意: 你可以假设树中没有重复的元素. 例如,给出 前序遍历 preorder = [3,9,20,15,7] 中 ...

  2. Leetcode 105. 从前序与中序遍历序列构造二叉树

    题目链接 题目描述 根据一棵树的前序遍历与中序遍历构造二叉树. 注意: 你可以假设树中没有重复的元素. 例如,给出 前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder ...

  3. LeetCode 105. 从前序与中序遍历序列构造二叉树(Construct Binary Tree from Preorder and Inorder Traversal)

    题目描述 根据一棵树的前序遍历与中序遍历构造二叉树. 注意:你可以假设树中没有重复的元素. 例如,给出 前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder = [9, ...

  4. [LeetCode]105. 从前序与中序遍历序列构造二叉树(递归)、108. 将有序数组转换为二叉搜索树(递归、二分)

    题目 05. 从前序与中序遍历序列构造二叉树 根据一棵树的前序遍历与中序遍历构造二叉树. 注意: 你可以假设树中没有重复的元素. 题解 使用HashMap记录当前子树根节点在中序遍历中的位置,方便每次 ...

  5. 【leetcode 105. 从前序与中序遍历序列构造二叉树】解题报告

    前往 中序,后序遍历构造二叉树, 中序,前序遍历构造二叉树 TreeNode* build(vector<int>& preorder, int l1, int r1, vecto ...

  6. leetcode题解:Construct Binary Tree from Preorder and Inorder Traversal (根据前序和中序遍历构造二叉树)

    题目: Given preorder and inorder traversal of a tree, construct the binary tree. Note:You may assume t ...

  7. leetcode 105从前序与中序遍历序列构造二叉树

    方法一:直接使用复制的数据递归:O(n)时间,O(n)空间,不计算递归栈空间: /** * Definition for a binary tree node. * struct TreeNode { ...

  8. [Leetcode] Construct binary tree from preorder and inorder travesal 利用前序和中续遍历构造二叉树

    Given preorder and inorder traversal of a tree, construct the binary tree. Note:  You may assume tha ...

  9. Leetcode:105. 从前序与中序遍历序列构造二叉树&106. 从中序与后序遍历序列构造二叉树

    Leetcode:105. 从前序与中序遍历序列构造二叉树&106. 从中序与后序遍历序列构造二叉树 Leetcode:105. 从前序与中序遍历序列构造二叉树&106. 从中序与后序 ...

随机推荐

  1. mysql 第一次启动及常用命令

    启动 mysql -u root -p 进入后 # 显示有几个数据库 mysql> show databases; +--------------------+ | Database | +-- ...

  2. 使用Windbg调试内核

    Windbg是微软开发的免费源码级调试工具.Windbg可以用于Kernel模式调试和用户模式调试,还可以调试Dump文件. 1.从http://www.microsoft.com/whdc/devt ...

  3. 接口(Interfaces)与反射(reflection) 如何利用字符串驱动不同的事件 动态地导入函数、模块

    标准库内部如何实现接口的 package main import ( "fmt" "io" "net/http" "os" ...

  4. 基于Netty的RPC架构学习笔记(九):自定义序列化协议

    文章目录 为什么需要自定义序列化协议

  5. 浅析AIDL的使用和工作原理

    AIDL是一种接口定义语言,用于生成可在Android设备上两个进程之间进行进程间通信(IPC)的代码. AIDL的使用 新建一个aidl文件,定义进程间通信的接口 // IStudentManage ...

  6. Bootstrap3的响应式缩略图幻灯轮播效果设计

    在线演示1 本地下载 HTML <div class="container">  <div class="col-md-12">  &l ...

  7. java调用scala 查询hbase数据

    问题:将scala打成jar包,提供给java调用,但是java一直提示找不到类 实现功能:利用spark查询hbase数据,然后提供给外部接口调用 我的方式:spark查询Hbase用scala实现 ...

  8. 偏函数-functools.partial

    1.概念:偏函数是2.5版本以后引进来的东西.属于函数式编程的一部分,使用偏函数可以通过有效地“冻结”那些预先确定的参数,来缓存函数参数,然后在运行时,当获得需要的剩余参数后,可以将他们解冻,传递到最 ...

  9. IOS配置cocos2d-x

    cd /Users/wyc/Desktop/cocos2d-x-3.16/tools/cocos2d-console/bin python cocos.py new HelloWorldDemo -p ...

  10. luaj使用 方法签名规则 Cocos2dxLuaJavaBridge

    function AndroidHandler:getParamJson()     local args = {nil}     local ok,ret = luaj.callStaticMeth ...