The topic of dry

Flip a binary tree.

Example:

Input:

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

Output:

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

Solution: Depth-first search

The end condition of the recursive function is root== NULL, which indicates that root is already a leaf node. Then record the right subtree of the current node to the left subtree, switch positions, and return root.

Code implementation:

 / * * *@param {TreeNode} root
  * @return {TreeNode}* /
 var invertTree = function (root) {
     doswap(root);
     return root
 };
 function doswap(root) {
     if (root == null) return null;
     let anode = doswap(root.left);
     let bnode = doswap(root.right);
     root.left=bnode;
     root.right=anode;
     return root
 }
 ​
Copy the code

\