xiannv / xiannv.github.io

blog
0 stars 0 forks source link

【剑指offer】javascript 面试题27. 二叉树的镜像 - 简单 #110

Open xiannv opened 4 years ago

xiannv commented 4 years ago

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

例如输入:

     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]

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

xiannv commented 4 years ago

方法一,递归

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var mirrorTree = function(root) {
    if(root==null)
        return null;

    let temp = root.left;
    root.left = root.right;
    root.right = temp;
    mirrorTree(root.left);
    mirrorTree(root.right);
    return root;
};
xiannv commented 4 years ago

方法二,前序遍历

var mirrorTree = function(root){
    if (root == null){
        return null;
    }
    let node = root;
    let stack = [];
    while (node != null || !stack.length==0){
        if (node != null){
            // 交换左右子树
            inventTreeNode(node);
            // 原先的先序遍历
            stack.push(node);
            node = node.left;
        }else {
            node = stack.pop();
            node = node.right;
        }
    }
    return root;
}
function inventTreeNode(node){
    let temp = node.left;
    node.left = node.right;
    node.right = temp;
}