Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.

1. Title Description

Leetcode226. Flip the binary tree

Given a binary tree root, flip the binary tree and return its root.

Example 1:

Input: root = [4,2,7,1,3,6,9]Copy the code

Example 2:

Input: root = [2,1,3]Copy the code

Example 3:

Input: root = [] Output: []Copy the code

Tip:

  • The number of nodes in the tree ranges from[0, 100] 内
  • -100 <= Node.val <= 100

Second, train of thought analysis

Invert binary tree, numerical symmetry;

recursive

No need to expand understanding, using semantic information of recursive functions to carry out programming. First, the left and right subtrees of the current node are switched, and then the left and right subtrees are recursively flipped.

If both the left and right subtrees of the current node root are reversed, swap the left and right subtrees of the root node directly

JavaScript code

/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
/ * * *@param {TreeNode} root
 * @return {TreeNode}* /
 // The first is recursive from root to child
var invertTree = function(root) {
    if(root == null) return root;
    let mid = root.left
    root.left = root.right;
    root.right = mid;
    invertTree(root.left);
    invertTree(root.right);
    return root
};

// Process the child nodes first, using recursive backtracking
var invertTree = function(root) {
    if(root == null) return root;
    let left = invertTree(root.left);
    let right = invertTree(root.right);
    root.left = right;
    root.right = left;
    return root
};
Copy the code

Four,