leetcode-105-从前序与中序遍历构造二叉树
题目描述:
方法一:
# 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-从前序与中序遍历构造二叉树的更多相关文章
- Java实现 LeetCode 105 从前序与中序遍历序列构造二叉树
105. 从前序与中序遍历序列构造二叉树 根据一棵树的前序遍历与中序遍历构造二叉树. 注意: 你可以假设树中没有重复的元素. 例如,给出 前序遍历 preorder = [3,9,20,15,7] 中 ...
- Leetcode 105. 从前序与中序遍历序列构造二叉树
题目链接 题目描述 根据一棵树的前序遍历与中序遍历构造二叉树. 注意: 你可以假设树中没有重复的元素. 例如,给出 前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder ...
- LeetCode 105. 从前序与中序遍历序列构造二叉树(Construct Binary Tree from Preorder and Inorder Traversal)
题目描述 根据一棵树的前序遍历与中序遍历构造二叉树. 注意:你可以假设树中没有重复的元素. 例如,给出 前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder = [9, ...
- [LeetCode]105. 从前序与中序遍历序列构造二叉树(递归)、108. 将有序数组转换为二叉搜索树(递归、二分)
题目 05. 从前序与中序遍历序列构造二叉树 根据一棵树的前序遍历与中序遍历构造二叉树. 注意: 你可以假设树中没有重复的元素. 题解 使用HashMap记录当前子树根节点在中序遍历中的位置,方便每次 ...
- 【leetcode 105. 从前序与中序遍历序列构造二叉树】解题报告
前往 中序,后序遍历构造二叉树, 中序,前序遍历构造二叉树 TreeNode* build(vector<int>& preorder, int l1, int r1, vecto ...
- 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 ...
- leetcode 105从前序与中序遍历序列构造二叉树
方法一:直接使用复制的数据递归:O(n)时间,O(n)空间,不计算递归栈空间: /** * Definition for a binary tree node. * struct TreeNode { ...
- [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 ...
- Leetcode:105. 从前序与中序遍历序列构造二叉树&106. 从中序与后序遍历序列构造二叉树
Leetcode:105. 从前序与中序遍历序列构造二叉树&106. 从中序与后序遍历序列构造二叉树 Leetcode:105. 从前序与中序遍历序列构造二叉树&106. 从中序与后序 ...
随机推荐
- 全局唯一标识符(GUID,Globally Unique Identifier)
全局唯一标识符(GUID,Globally Unique Identifier)是一种由算法生成的二进制长度为128位的数字标识符.GUID主要用于在拥有多个节点.多台计算机的网络或系统中.在理想情况 ...
- 实战CGLib系列之proxy篇(一):方法拦截MethodInterceptor
实战CGLib系列文章 本篇介绍通过MethodInterceptor和Enhancer实现一个动态代理. 一.首先说一下JDK中的动态代理: JDK中的动态代理是通过反射类Proxy以及Invoca ...
- POJ-1836-Alignment-双向LIS(最长上升子序列)(LIS+LSD)+dp
In the army, a platoon is composed by n soldiers. During the morning inspection, the soldiers are al ...
- 2019 牛客多校第五场 B generator 1
题目链接:https://ac.nowcoder.com/acm/contest/885/B 题目大意 略. 分析 十进制矩阵快速幂. 代码如下 #include <bits/stdc++.h& ...
- Redis基于主从复制的RCE(redis4.x 5.x)复现
使用docker建立redis 拉取镜像 运行 查看 可以连接,存在未授权 https://github.com/Ridter/redis-rce 发送poc i:正向连接 r:反弹 反弹成功
- 解决OCX 在 非开发电脑上注册出错的问题
这几天遇到一个问题,就是在我自己电脑上开发的OCX 放在其他电脑上居然注册失败,管理员运行也不行,老是会蹦出这样的错误,最后呢终于让我找到一个线索就是在开发电脑上可以安装,在无开发环境上很大概率安装失 ...
- CSIC_716_20191104【流程控制语句】
流程控制语句 if 语法结构 if 逻辑判断为真 : xxxxxx else: xxxxx while 语法结构 (continue.break) while 逻辑判断为真: xxxxxxx con ...
- 关于jquery ajax项目总结
$.ajax({ url:"../action/BorrowAction.php?action=oready", async:true,//异步请求 ...
- scala 中List的简单使用
/** * scala 中List的使用 * */ object ListUse { def main(args: Array[String]): Unit = { def decorator(l:L ...
- 暴力剪枝——cf1181C
暴力求长度为len时,以i,j为左上角的旗子的数量 不剪枝的话复杂度是n*n*m*n,必定超时 两个可以剪枝的地方:如果格子[i,j]可以作为长度为len的旗子的左上角,那么其必定不可以作为长度> ...