数据结构与算法每日一题——二叉树(226. 翻转二叉树)

86 阅读1分钟

226. 翻转二叉树

/**
 * 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 invertTree = function (root) {
    if (root === null) {
        return null;
    }
    const left = invertTree(root.left);
    const right = invertTree(root.right);
    root.left = right;
    root.right = left;
    return root;

};

var invertTree = function (root) {
    // 递归的方法
    if (root === null) return root;
    // 交换当前节点的左右子树
    [root.left, root.right] = [invertTree(root.right), invertTree(root.left)];
    return root;
};

var invertTree = function (root) {
    if (root === null) return root;
    // 声明队列用于存储后续数据
    const queue = [root];
    // 遍历队列
    while (queue.length) {
        // 一层的数据量
        let len = queue.length
        while (len > 0) {
            // 将本次操作的结点出队
            const node = queue.shift()
            let tmp = node.right;
            node.right = node.left;
            node.left = tmp;
            // 检测是否存在左右子结点,如果有,入队即可
            node.left && queue.push(node.left)
            node.right && queue.push(node.right)
            len--
        }
    }

    return root;
};