# [226] 翻转二叉树

翻转一棵二叉树。

示例:

输入:

⁠ ⁠  ⁠4

⁠ ⁠ /⁠ \

 2  7

 ⁠/ \  / \

1 3 6 9

输出:

⁠ ⁠  ⁠4

⁠ ⁠ /⁠ \

 7  2

 ⁠/ \  / \

9 6 3 1

树深度优先遍历(递归)与层序遍历(队列,非递归)两种方法

var invertTree = function(root) {
  if (!root) return null;
  invertTree(root.left);
  invertTree(root.right);

  const temp = root.left;
  root.left = root.right;
  root.right = temp;

  return root;
};

function TreeNode(val) {
  this.val = val;
  this.left = this.right = null;
}
var invertTree = function(root) {
  if (!root) return null;
  const queue = [root];
  while (queue.length !== 0) {
    const node = queue.shift();
    const 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;
};