The title

Flip a binary tree.

Example:

Input:

4 / \ 27 / \ / \ 1 3 6 9Copy the code

Output:

4 / \ 7 2 / \ / 9 6 3 1Copy the code

Source: LeetCode leetcode-cn.com/problems/in…

Their thinking

  1. Use the idea of divide and conquer
  2. Swap the left and right subtrees of the root node
  3. Recursively flip the left and right subtrees

Code implementation

var invertTree = function(root) { if (! root) return root; [root.left, root.right] = [root.right, root.left] invertTree(root.left) invertTree(root.left) return root};Copy the code

If there are mistakes welcome to point out, welcome to discuss together!