剑指Offer JZ18 二叉树的镜像(JavaScript)

时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M 热度指数:12439
本题知识点: 树
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
比如: 源二叉树

    8
   /  \
  6   10
 / \  / \
5  7 9 11
镜像二叉树
    8
   /  \
  10   6
 / \  / \
11 9 7  5

示例1
输入
{8,6,10,5,7,9,11}
返回值
{8,10,6,11,9,7,5}

思路:递归交换左右子树,由于子树的子节点也会跟随节点移动,所以每次只需要左右节点互换即可。

function Mirror(pRoot) {
    
    
    // write code here
    if (!pRoot) return pRoot
    let target = pRoot.left
    pRoot.left = pRoot.right
    pRoot.right = target
    Mirror(pRoot.left)
    Mirror(pRoot.right)
    return pRoot
}

思路同上,拆分出子函数

function Mirror(pRoot) {
    
    
    // write code here
    if (!pRoot) return pRoot
    sub(pRoot)
    return pRoot
}

function sub(root) {
    
    
    let target = root.left
    root.left = root.right
    root.right = target
    if (root.left) {
    
    
        sub(root.left)
    }
    if (root.right) {
    
    
        sub(root.right)
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44523860/article/details/115012528