翻转一棵二叉树。

  1. 输入:
  2. 4
  3. / \
  4. 2 7
  5. / \ / \
  6. 1 3 6 9
  7. 输出:
  8. 4
  9. / \
  10. 7 2
  11. / \ / \
  12. 9 6 3 1

二叉树后序遍历:

  1. // 将整棵树的节点翻转
  2. const invertTree = function invertTree(root) {
  3. if (!root) return null;
  4. [root.left, root.right] = [root.right, root.left];
  5. invertTree(root.left);
  6. invertTree(root.right);
  7. return root;
  8. }

命令式写法

  1. const mirrorTree = function mirrorTree( root) {
  2. if (!root) return null;
  3. [root.left, root.right] = [mirrorTree(root.right), mirrorTree(root.left)];
  4. return root;
  5. }

函数式写法

  1. const mirrorTree = function mirrorTree( root) {
  2. if (!root) return null;
  3. return Tree(node.value, mirrorTree(node.right), mirrorTree(node.left));
  4. }

BFS

  1. var invertTree = function(root) {
  2. if(!root) return root;
  3. const q = [root];
  4. while(q.length) {
  5. const node = q.shift();
  6. // 交换左右子树
  7. [node.left, node.right] = [node.right, node.left];
  8. if(node.left) q.push(node.left);
  9. if(node.right) q.push(node.right);
  10. }
  11. return root;
  12. };