《剑指offer》JavaScript版(4-6题)

4、重建二叉树

问题描述

  输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

实现思路

  前序遍历是先访问根节点,再访问左子树,再访问右子树。那么前序遍历序列的第一个数字就是根节点。中序遍历是先访问左子树,再访问根节点,最后访问右子树。那么中序遍历根节点左边的序列就是左子树,右边的序列就是右子树。依次递归。

代码

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function reConstructBinaryTree(pre, vin)
{
    // write code here
    if(!pre||pre.length===0){
        return ;
    }
    var treeNode=new treeNode(pre[0]);
    if(var i=0;i<pre.length;i++){
        if(vin[i]===pre[0]){
            treeNode.left=reConstructBinaryTree(pre.slice(1,i+1),vin(0,i));
treeNode.right=reConstructBinaryTree(pre.slice(i+1),vin(i+1));    
    
}
}
return treeNode;
}

5、用两个栈实现队列

问题描述

  用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

实现思路

  先创建一个栈,可以实现插入、删除和判空。再初始化两个栈,一个用来push,一个用来pop。

代码

function Stack(){
    var item=[];
    this.push()=function(node){
        item.push(node);    
    }
    this.pop()=function(){
        item.pop();
    }
    this.isEmpty()=function(){
        return  item.length===0;
    }
}
var stack1=new Stack();
var stack2=new Stack();
function push(node)
{
    return stack1.push(node);
}
function pop()
{
    if(stack1.isEmpty()&&stack2.isEmpty()){
        alert("stack is empty");
    }
    if(stack2.isEmpyt()){
        while(!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }
    }
    return stack2.pop();
}

 

6、旋转数组的最小数字

问题描述

  把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。

实现思路

  类似二分查找,起始位置设为low,终止位置设为high,mid=low+Math.floor(high-low)/2,然后将high对应的值与mid对应的值比较,如果high比mid小,则low=mid+1,否则high=mid,依次递归。

代码

function minNumberInRotateArray(rotateArray)
{
    var len = rotateArray.length
    if (len == 0){
        return 0
    }else{ 
        var low = 0;
        var high = len-1;
        while(low<high){
            var mid = low + Math.floor((high - low) / 2);        
            if(rotateArray[mid] > rotateArray[high]){
                low = mid + 1;
            }else if(rotateArray[mid] == rotateArray[high]){
                high = high - 1;
            }else{
                high = mid;
            }   
        }
        return rotateArray[low];
        }
    }

 

posted @ 2017-08-02 10:59  水迹仙涯  阅读(226)  评论(0编辑  收藏  举报