剑指offer 二叉树的镜像

72 阅读1分钟

一 题目

二 代码

//方案一:递归解法
//时间复杂度:O(n), n为树节点的个数。每个节点只用遍历一次,所以为O(n)
//空间复杂度:O(n), 每个节点都会在递归栈中存一次
var invertTree = function(root) {
    //如果节点为空,直接返回节点
    if(root===null) return null;
    //借助temp变量交换root.left和root.right的值
    let temp=root.left;
    root.left=root.right;
    root.right=temp;
    //翻转左右子树
    invertTree(root.left);
    invertTree(root.right);
    return root;
};

//方案二:非递归解法
//广度优先
function Mirror(root)
{
    if(!root) return null;
    let queue=[];
    queue.push(root);
    while(queue.length){
        let len=queue.length;
        for(let i=0;i<len;i++){
            let node=queue.shift();
            let temp=node.left;
            node.left=node.right;
            node.right=temp;
            if(node.left){
                queue.push(node.left);
            }
            if(node.right){
                queue.push(node.right);
            } 
        }
    }
    return root;
}