这是我参与8月更文挑战的第17天,活动详情查看:8月更文挑战
重建二叉树
剑指Offer 07.重建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
限制:0 <= 节点个数 <= 5000
题解
首先我们要明白前序遍历和中序遍历的节点遍历顺序。
前序遍历:根->左->右
中序遍历:左->根->右
根据题目我们可以得到:
前序遍历的根节点,在中序遍历中它的位置左侧是左子树,右侧是右子树。在中序遍历获取的索引中可以帮助我们划分前序数组,所以我们可以通过得到的数组递归得到叶子节点,最后通过回溯的方法,组装成一棵完整的树。
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {number[]} preorder
* @param {number[]} inorder
* @return {TreeNode}
*/
var buildTree = function(preorder, inorder){
if(preorder.length === 0) return null
const cur = new TreeNode(preorder[0]) // 获取根节点
const index = inorder.indexOf(preorder[0]) // 获取中序数组中根节点的位置
cur.left = buildTree(preorder.slice(1,index+1),inorder.slice(0,index))
cur.right = buildTree(preorder.slice(index+1),inorder.slice(index+1))
return cur
}
用两个栈实现队列
剑指Offer 09.用两个栈实现队列
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead操作返回 -1)
示例1:
输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]
示例2:
输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]
提示:
- 1 <= values <= 10000
- 最多会对 appendTail、deleteHead 进行 10000 次调用
题解
队列:先入先出 栈:后入先出
根据题意,两个栈分工不同,一个为入队栈,一个为出队栈,各自负责入队和出队。
入队操作,直接压入入队栈即可,出队操作需要先检查出队栈有无数据,若无,需要从入队栈出栈导入到出队栈后再出栈即可。
var CQueue = function(){
this.stack1 = [] // 入队栈
this.stack2 = [] // 出队栈
};
/**
* @param {number} value
* @return {void}
*/
CQueue.prototype.appendTail = function(value){
this.stack1.push(value)
};
/**
* @return {number}
*/
CQueue.prototype.deleteHead = function(){
if(this.stack2.length){
return this.stack2.pop()
}else{
while(this.stack1.length){
this.stack2.push(this.stack1.pop())
}
if(!this.stack2.length){
return -1;
}else{
return this.stack2.pop()
}
}
};
/**
* Your CQueue object will be instantiated and called as such:
* var obj = new CQueue()
* obj.appendTail(value)
* var param_2 = obj.deleteHead()
*/
坚持每日一练!前端小萌新一枚,希望能点个赞哇~