力扣-翻转二叉树

108 阅读1分钟

题地址:leetcode-cn.com/problems/in…

题解1: 处理边界, 如果没有根节点直接返回null 维护一个元组空间,进行遍历,每次弹出头部,记录一下left,right的值并进行反转 判断为left或right时,防止为null,将其入列

 * @param {TreeNode} root
 * @return {TreeNode}
 */
var invertTree = function(root) {
    if(!root) return null
    const stak = [root]
    while(stak.length) {
        const cur = stak.shift()
        const left = cur.left
        const right = cur.right
        cur.right = left
        cur.left  = right
        if(cur.left) {
            stak.push(right)
        }
        if(cur.right) {
            stak.push(left)
        }
    }
    return root
};

题解2: 直接递归翻转left,right, 下面的字节点跟着一起翻转

function reverseNode(root) {
    const left = root.left
    const right = root.right
    root.left  = right
    root.right = left
    reverse(root.left)
    reverse(root.right)
    return root
}