108. 将有序数组转换为二叉搜索树

思路:此数组为升序数组,为树的中序遍历结果。可以每次寻找中间结点作为树的根节点。以此为递归循环进行递归。

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} nums
 * @return {TreeNode}
 */
var sortedArrayToBST = function(nums) {
    if(!nums.length){
        return null;
    }
    let headIndex=Math.floor(nums.length/2);
    let head=new TreeNode(nums[headIndex]);
    let left=headIndex-1;
    let right=headIndex+1;
    if(left>=0){
        head.left=sortedArrayToBST(nums.slice(0,headIndex));
    }
    if(right<nums.length){
        head.right=sortedArrayToBST(nums.slice(right))
    }
    return head;
};

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

思路:每次从先序遍历中拿出根节点,再在中序遍历中定位到位置。即可计算出左子树和右子树的节点数目。根据节点数目,拆分先序遍历数组,进行递归。每次创建根节点。

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} preorder
 * @param {number[]} inorder
 * @return {TreeNode}
 */
var buildTree = function(preorder, inorder) {
    if(preorder.length===0||inorder.length===0) return null;
    let root = new TreeNode(preorder[0]);
    let rootIndex=inorder.indexOf(preorder[0]);
    root.left=buildTree(preorder.slice(1,rootIndex+1),inorder.slice(0,rootIndex));
    root.right=buildTree(preorder.slice(rootIndex+1),inorder.slice(rootIndex+1));
    return root;
};

103. 二叉树的锯齿形层序遍历

思路:层序遍历,再将奇数层逆序

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var zigzagLevelOrder = function(root) {
    let res=[];
    if(!root) return res;
    let queue=[root]
    while(queue.length){
        let arr=[];
        let len=queue.length;
        for(let i=0;i<len;i++){
            let node=queue.shift();
            arr.push(node.val);
            node.left&&queue.push(node.left);
            node.right&&queue.push(node.right)
        }
        res.push(arr)
    }
    for(let i=0;i<res.length;i++){
        if(i%2===1){
            res[i].reverse();
        }
    }
    return res;
};