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. 从中序与后序 ...
随机推荐
- Java-javaFx库运用-自动弹跳的球
(1)定义一个名为BallPane的类,用于显示一个弹动的球: (2)定义一个名为BounceBallControl的类,用来使用鼠标动作控制弹球,当鼠标按下的时候动画暂停,当鼠标释放的时候动画恢复执 ...
- 牛客练习赛43D Tachibana Kanade Loves Sequence
题目链接:https://ac.nowcoder.com/acm/contest/548/D 题目大意 略 分析 贪心,首先小于等于 1 的数肯定不会被选到,因为选择一个数的代价是 1,必须选择大于1 ...
- Python3 From Zero——{最初的意识:002~字符串和文本}
一.使用多个界定符分割字符串 字符串.split(',')形式只适用于单一分割符的情况:多分割符同时应用的时候,可使用re.split() >>> line = 'asdf fjdk ...
- 2018今日头条湖北省赛【H】
[题目链接]https://www.nowcoder.com/acm/contest/104/G 现场赛的H题,emmm...C++选手表示很伤心.高精度压四位板子WA四发. 题意很简单就是给你n个数 ...
- 数组模拟stack
package com.cxy.springdataredis.data; import java.util.Scanner; public class StackDemo { public stat ...
- Android开发 Button的开发记录
Button置顶层效果取消 android:stateListAnimator="@null" 在代码里执行点击 mButton.performClick(); //点击 mBut ...
- Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0
android studio 3.0 出现此问题可能是因为 你的android studio 时脱机状态 无法下载资源 这时候你可以点击左上角分File->Other Settings-> ...
- layer.confirm等事件X关闭与取消监听
关于layer.confirm的所有操作 layer.confirm('content',{ btn:['确定','取消'], cancel:function(index, layero){ cons ...
- Java带头节点单链表的增删合并以及是否有环
带头节点单链表 1.优势: 1)当链表为空时,指针指向头结点,不会发生null指针异常 2)方便特殊操作(删除第一个有效节点或者插入一个节点在表头) 3)单链表加上头结点之后,无论单链表是否为空,头指 ...
- (依赖注入框架:Ninject ) 一 手写依赖注入
什么是依赖注入? 这里有一个场景:战士拿着刀去战斗: 刀: class Sword { public void Hit(string target) { Console.WriteLine($&quo ...