# 二叉树的镜像(翻转二叉树)

leetcode - 226. 翻转二叉树 (opens new window)

# 题目

操作给定的二叉树,将其变换为源二叉树的镜像。

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

# 思路

递归交换二叉树所有节点左右节点的位置。

# 代码

# Johninch

var invertTree = function(root) {
    if (!root) {
        return null
	}

	[root.left, root.right] = [invertTree(root.right), invertTree(root.left)]

	return root
};

var invertTree = function(root) {
    if (!root) {
        return null
    }

    const stack = [root]
    let current = null
    while(current = stack.shift()) {
        const left = current.left
        const right = current.right
        current.left = right
        current.right = left

      if (left) {
        stack.push(left)
      }

      if (right) {
        stack.push(right)
      }
    }

    return root
}

# niannings

function toImage(tree: IBinaryTreeBase) {
    if (tree.isEmpty()) return tree; // 空树
    const Q = [tree.root];
    while (Q.length) {
        const p = Q.shift();
        const l = p.left;
        const r = p.right;
        if (l === null && r === null) break; // 只有根节点
        p.left = r;
        p.right = l;
        if (l !== null) Q.push(l);
        if (r !== null) Q.push(r);
    }
    return tree;
}

# febcat

const reverse = node => {
    if (!node) {
      return null;
    }

    let nodeLeft = node.left;
    let nodeRight = node.right;
    node = new Node(node.data);

    if (nodeRight) {
      node.left = _reverse(nodeRight);
    }
    if (nodeLeft) {
      node.right = _reverse(nodeLeft);
    }

    return node;
  };
Last Updated: 9/14/2020, 5:59:29 PM