leetcode 2 | 刷题打卡

139 阅读1分钟

题目描述

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

例如输入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9
镜像输出:

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

 

示例 1:

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

限制:

0 <= 节点个数 <= 1000

思路分析

该题有两种实现方式:1.利用递归。 2.利用栈。

AC代码

// 利用递归
var mirrorTree = function(root) {
    if(!root) {
        return null
    }

    let temp = root.right
    root.right = mirrorTree(root.left)
    root.left = mirrorTree(temp)

    return root
};
// 利用栈
var mirrorTree = root => {
    if(!root) {
        return root
    }

    let stack = [root]
    while(stack.length) {
        let node = stack.pop()
        let temp = node.right
        node.right = node.left
        node.left = temp
        node.right && stack.push(node.right)
        node.left && stack.push(node.left)
    }

    return root
}

总结

注意栈在两两交换顺序场景下的应用