【leetcode】226.翻转二叉树

75 阅读1分钟

leetcode-226.png

BFS

这里采用的是stack,而不是queue,使用pop 因为这里涉及到一个时间优化的问题,使用shift的时候,会让数组都向前挪动一位,时间复杂度是n 直接采用pop就不会出现这个问题

var invertTree = function (root) {
    if (!root) return root
    let stack = [root]
    while (stack.length) {
        let size = stack.length
        for (let i = 0; i < size; ++i) {
            let node = stack.pop()
            let tmp = node.left
            node.left = node.right
            node.right = tmp
            if (node.left) stack.push(node.left)
            if (node.right) stack.push(node.right)
        }
    }
    return root
};

DFS

有时候写树的DFS,就需要一点逻辑上的通畅
下面这段代码,如果要仔细的在脑袋里面递归理解,我感觉要爆炸
如果直接就这么写,理解起来貌似也没错误,然后也能ac

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