力扣226. 翻转二叉树(JavaScript)

方法一:递归

var invertTree = function(root) {
    let swap=function(left,right){
        let temp=left
        left=right
        right=temp
        //重新赋值
        root.left=left
        root.right=right
    }
    if(root===null){
        return root
    }
    swap(root.left,root.right)
    invertTree(root.left)
    invertTree(root.right)
    return root
};

方法二:迭代(前序迭代)

var invertTree = function(root) {
    
    let swap=function(node1,left,right){
        let temp=left
        left=right
        right=temp
        //重新赋值
        node1.left=left
        node1.right=right
    }
    if(root===null){
        return root
    }
    /*前序迭代*/
    let s=[root]
    while(s.length){
        let node=s.pop()
        if(node===null){
            //调换左右子树
            let node1=s.pop()
            swap(node1,node1.left,node1.right)
            continue
        }
        //右
        node.right&&s.push(node.right)
        //左
        node.left&&s.push(node.left)
        //根
        s.push(node)
        s.push(null)
    }
    return root
};

方法三:层序遍历

var invertTree = function(root) {
    
    let swap=function(node1,left,right){
        let temp=left
        left=right
        right=temp
        //重新赋值
        node1.left=left
        node1.right=right
    }
    if(root===null){
        return root
    }
    let q=[root]
   while(q.length){
       let len=q.length
       for(let i=0;i

你可能感兴趣的:(力扣算法题,leetcode,javascript,算法)