LeetCode刷题 Day15

66 阅读1分钟

LeetCode刷题 Day15

226. Invert Binary Tree

Given the root of a binary tree, invert the tree, and return its root.

  Example 1:

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Example 2:

Input: root = [2,1,3]
Output: [2,3,1]

Example 3:

Input: root = []
Output: []

思路:

  • 利用先序遍历交换节点 再逐层返回

代码:

var invertTree = function(root) {
    if (!root) return null;
    
    let temp = root.left;
    root.left = root.right;
    root.right = temp;

    invertTree(root.left);
    invertTree(root.right);
    
    return root;
};

时间复杂度: O(n), 空间复杂度: O(n)


101. Symmetric Tree

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

  Example 1:

Input: root = [1,2,2,3,4,4,3]
Output: true

Example 2:

Input: root = [1,2,2,null,3,null,3]
Output: false

思路:

  • 使用辅助函数,参数为root.left, root.right
  • 为了避免null error, 需要做空节点判断 (!left && !right) return true; (!left || !right) return false;

代码:

var isSymmetric = function(root) {
    if (!root) return true;
    
    var helper = function(left, right) {
        if (!left && !right) return true;
        if (!left || !right) return false;

        return left.val === right.val && 
               helper(left.left, right.right) &&
               helper(left.right, right.left);
    
    }
    
    return helper(root.left, root.right);
};

时间复杂度: O(n), 空间复杂度: O(n)