剑指offer_27_二叉树的镜像【javascript】

68 阅读1分钟

题目

请完成一个函数,输入一个二叉树,该函数输出它的镜像

示例

/** 
 *                     4                            4
 *                   /   \                        /   \
 *                  2     7                      7     2
 *                 / \   / \                   /  \   /  \
 *                1   3 6   9                 9   6  3   1     
*/

输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

限制:

  • 0 <= 节点个数 <= 1000

题解

递归(深度)

 * 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;
};

算法复杂度分析

  • 时间复杂度:O(N)
  • 空间复杂度:O(N)

遍历(广度)

/**
 * 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 queue = [root];
    while(queue.length > 0) {
        let temp = queue.shift();
        let left = temp.left;
        temp.left = temp.right;
        temp.right = left;
        if (temp.left) {
            queue.push(temp.left);
        }
        if (temp.right) {
            queue.push(temp.right);
        }
    }
    return root;
};

算法复杂度分析

  • 时间复杂度:O(N)
  • 空间复杂度:O(N)

引用

  • 剑指offer书籍
  • 力扣题解