LeetCode 新一期二叉树

94 阅读2分钟

653. 两数之和 IV - 输入 BST

653. 两数之和 IV - 输入 BST

/**
 * 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
 * @param {number} k
 * @return {boolean}
 */
/* 
    方法1: 中序遍历,+ 双指针法
    方法2: 使用Set + 递归
*/
var findTarget = function(root, k) {
    const list = [];
    function BST(root) {
        if (root === null) return;
        BST(root.left);
        list.push(root.val);
        BST(root.right);
    }
    BST(root);
    let left = 0;
    let right = list.length - 1;
    while (left < right) {
        const sum = list[left] + list[right];
        if (sum === k) return true
        else if (sum > k) {
            right -= 1;
        } else if (sum < k) {
            left += 1;
        }
    }
    return false;
};

671. 二叉树中第二小的节点

671. 二叉树中第二小的节点

/**
 * 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 findSecondMinimumValue = function(root) {
    let res = -1;
    let rootValue = root.val;
    function dfs(root) {
        if (root === null) return;
        /* 如果res 有值了  */
        if (res !== -1 && root.val >= res) {
            return;
        }
        if (root.val > rootValue) {
            res = root.val;
        }
        dfs(root.left);
        dfs(root.right);
    }
    dfs(root);
    return res;
};

700. 二叉搜索树中的搜索

700. 二叉搜索树中的搜索

/**
 * 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
 * @param {number} val
 * @return {TreeNode}
 */
/* 
    这个题目单纯的递归就可以了
*/
var searchBST = function(root, val) {
    if (root == null) return null;
    if (val === root.val) {
        return root;
    }
    return searchBST(root.val > val ? root.left : root.right, val);
};

703. 数据流中的第 K 大元素

703. 数据流中的第 K 大元素

/**
 * @param {number} k
 * @param {number[]} nums
 */
var KthLargest = function(k, nums) {
    this.k = k;
    this.heap = new MinHeap();
    for (const x of nums) {
        this.add(x);
    }
};

KthLargest.prototype.add = function(val) {
    this.heap.offer(val);
    if (this.heap.size() > this.k) {
        this.heap.poll();
    }
    return this.heap.peek();
};

class MinHeap {
    constructor(data = []) {
        this.data = data;
        this.comparator = (a, b) => a - b;
        this.heapify();
    }

    heapify() {
        if (this.size() < 2) return;
        for (let i = 1; i < this.size(); i++) {
        this.bubbleUp(i);
        }
    }

    peek() {
        if (this.size() === 0) return null;
        return this.data[0];
    }

    offer(value) {
        this.data.push(value);
        this.bubbleUp(this.size() - 1);
    }

    poll() {
        if (this.size() === 0) {
            return null;
        }
        const result = this.data[0];
        const last = this.data.pop();
        if (this.size() !== 0) {
            this.data[0] = last;
            this.bubbleDown(0);
        }
        return result;
    }

    bubbleUp(index) {
        while (index > 0) {
            const parentIndex = (index - 1) >> 1;
            if (this.comparator(this.data[index], this.data[parentIndex]) < 0) {
                this.swap(index, parentIndex);
                index = parentIndex;
            } else {
                break;
            }
        }
    }

    bubbleDown(index) {
        const lastIndex = this.size() - 1;
        while (true) {
            const leftIndex = index * 2 + 1;
            const rightIndex = index * 2 + 2;
            let findIndex = index;
            if (
                leftIndex <= lastIndex &&
                this.comparator(this.data[leftIndex], this.data[findIndex]) < 0
            ) {
                findIndex = leftIndex;
            }
            if (
                rightIndex <= lastIndex &&
                this.comparator(this.data[rightIndex], this.data[findIndex]) < 0
            ) {
                findIndex = rightIndex;
            }
            if (index !== findIndex) {
                this.swap(index, findIndex);
                index = findIndex;
            } else {
                break;
            }
        }
    }

  swap(index1, index2) {
        [this.data[index1], this.data[index2]] = [this.data[index2], this.data[index1]];
    }

    size() {
        return this.data.length;
    }
}
/**
 * Your KthLargest object will be instantiated and called as such:
 * var obj = new KthLargest(k, nums)
 * var param_1 = obj.add(val)
 */

872. 叶子相似的树

872. 叶子相似的树

/**
 * 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} root1
 * @param {TreeNode} root2
 * @return {boolean}
 */

/* 
    DFS 深度优先遍历,把叶子节点放在数组里
    然后,对比数组就可以了
*/
var leafSimilar = function(root1, root2) {
    function dfs(root, arr) {
        if (!root.left && !root.right) {
            arr.push(root.val);
            return;
        }
        root.left && dfs(root.left, arr);
        root.right && dfs(root.right, arr);
    }
    const arr1 = [];
    if (root1) {
        dfs(root1, arr1);
    }
    const arr2 = [];
    if (root2) {
        dfs(root2, arr2);
    }
    return arr1.toString() === arr2.toString();
};

897. 递增顺序搜索树

897. 递增顺序搜索树

/**
 * 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 {TreeNode}
 */
/* 
    先中序遍历,放到数组里
    再创建新的二叉树
*/
var increasingBST = function(root) {
    const res = [];
    function inorder(node, arr) {
        if (!node) return;
        inorder(node.left, arr);
        arr.push(node.val);
        inorder(node.right, arr);
    }
    inorder(root, res);

    let resNode = new TreeNode(-1);
    let cur = resNode;
    for(let val of res) {
        cur.right = new TreeNode(val);
        cur = cur.right;
    }
    return resNode.right;
};

938. 二叉搜索树的范围和

938. 二叉搜索树的范围和

/**
 * 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
 * @param {number} low
 * @param {number} high
 * @return {number}
 */
var rangeSumBST = function(root, low, high) {
    if (!root) return null;
    let sum = 0;
    function bst(node) {
        if (!node) return;
        bst(node.left);
        if (node.val >= low && node.val <= high) {
            sum += node.val;
        }
        bst(node.right);
    }
    bst(root);
    return sum;
};

965. 单值二叉树

965. 单值二叉树

/**
 * 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 {boolean}
 */
var isUnivalTree = function(root) {
    if (!root) return true;
    let num = root.val;
    let isUnival = true;
    function dfs(root) {
        if (root == null || !isUnival) return;
        if (root.val !== num) {
            isUnival = false;
            return;
        }
        root.left && dfs(root.left);
        root.right && dfs(root.right);
    }
    dfs(root)
    return isUnival;
};

993. 二叉树的堂兄弟节点

993. 二叉树的堂兄弟节点

/**
 * 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
 * @param {number} x
 * @param {number} y
 * @return {boolean}
 */
var isCousins = function(root, x, y) {
    // x 的信息
    let x_parent = null, x_depth = null, x_found = false;
    // y 的信息
    let y_parent = null, y_depth = null, y_found = false;
    
    const dfs = (node, depth, parent) => {
        if (!node) {
            return;
        }
        if (node.val === x) {
            [x_parent, x_depth, x_found] = [parent, depth, true];
        } else if (node.val === y) {
            [y_parent, y_depth, y_found] = [parent, depth, true];
        }

        // 如果两个节点都找到了,就可以提前退出遍历
        // 即使不提前退出,对最坏情况下的时间复杂度也不会有影响
        if (x_found && y_found) {
            return;
        }

        dfs(node.left, depth + 1, node);

        if (x_found && y_found) {
            return;
        }

        dfs(node.right, depth + 1, node);
    }
    dfs(root, 0, null);
    return x_depth === y_depth && x_parent !== y_parent;
};

LCP 44. 开幕式焰火

LCP 44. 开幕式焰火

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var numColor = function(root) {
     let mySet = new Set();
    if (!root) return 0;
    function dfs(node) {
        if (!node) return;
        mySet.add(node.val);
        dfs(node.left);
        dfs(node.right);
    }
    dfs(root);
    return mySet.size;
};

剑指 Offer II 059. 数据流的第 K 大数值

剑指 Offer II 059. 数据流的第 K 大数值

/**
 * @param {number} k
 * @param {number[]} nums
 */
var KthLargest = function(k, nums) {
    this.k = k;
    this.heap = new MinHeap();
    for (const x of nums) {
        this.add(x);
    }
};

KthLargest.prototype.add = function(val) {
    this.heap.offer(val);
    if (this.heap.size() > this.k) {
        this.heap.poll();
    }
    return this.heap.peek();
};

class MinHeap {
    constructor(data = []) {
        this.data = data;
        this.comparator = (a, b) => a - b;
        this.heapify();
    }

    heapify() {
        if (this.size() < 2) return;
        for (let i = 1; i < this.size(); i++) {
        this.bubbleUp(i);
        }
    }

    peek() {
        if (this.size() === 0) return null;
        return this.data[0];
    }

    offer(value) {
        this.data.push(value);
        this.bubbleUp(this.size() - 1);
    }

    poll() {
        if (this.size() === 0) {
            return null;
        }
        const result = this.data[0];
        const last = this.data.pop();
        if (this.size() !== 0) {
            this.data[0] = last;
            this.bubbleDown(0);
        }
        return result;
    }

    bubbleUp(index) {
        while (index > 0) {
            const parentIndex = (index - 1) >> 1;
            if (this.comparator(this.data[index], this.data[parentIndex]) < 0) {
                this.swap(index, parentIndex);
                index = parentIndex;
            } else {
                break;
            }
        }
    }

    bubbleDown(index) {
        const lastIndex = this.size() - 1;
        while (true) {
            const leftIndex = index * 2 + 1;
            const rightIndex = index * 2 + 2;
            let findIndex = index;
            if (
                leftIndex <= lastIndex &&
                this.comparator(this.data[leftIndex], this.data[findIndex]) < 0
            ) {
                findIndex = leftIndex;
            }
            if (
                rightIndex <= lastIndex &&
                this.comparator(this.data[rightIndex], this.data[findIndex]) < 0
            ) {
                findIndex = rightIndex;
            }
            if (index !== findIndex) {
                this.swap(index, findIndex);
                index = findIndex;
            } else {
                break;
            }
        }
    }

  swap(index1, index2) {
        [this.data[index1], this.data[index2]] = [this.data[index2], this.data[index1]];
    }

    size() {
        return this.data.length;
    }
}
/**
 * Your KthLargest object will be instantiated and called as such:
 * var obj = new KthLargest(k, nums)
 * var param_1 = obj.add(val)
 */