美文网首页
226. Invert Binary Tree

226. Invert Binary Tree

作者: jluemmmm | 来源:发表于2020-09-05 12:01 被阅读0次

递归实现

  • Runtime: 68 ms, faster than 94.35%
  • Memory Usage: 37.1 MB, less than 27.88%
  • 时间复杂度 O(n)
  • 空间复杂度O(h)--->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) return null
    let left = invertTree(root.left)
    let right = invertTree(root.right)
    root.left = right
    root.right = left
    return root
};

迭代实现

  • Runtime: 76 ms, faster than 68.04%
  • Memory Usage: 36.9 MB, less than 54.25%
  • 时间复杂度 O(n)
  • 空间复杂度 O(n),最坏情况下,队列中包含树中的所有节点O(\frac{n}{2}) --> O(n)

深度优先遍历方法实现

var invertTree = function(root) {
    if(!root) return null
    let queue = [root]
    while(queue.length) {
        let n = queue.length
        let node = queue.shift()
        let left = node.left
        node.left = node.right
        node.right = left
        node.left && queue.push(node.left)
        node.right && queue.push(node.right)
    }
    return root
};

相关文章

网友评论

      本文标题:226. Invert Binary Tree

      本文链接:https://www.haomeiwen.com/subject/xwnxektx.html