LeetCode-226-Flip Binary Tree (Simple)


1. Description

Flip a binary tree.

2. Example

enter:
Insert picture description here

Output:
Insert picture description here

3. Analysis

Observe the input and output, take node "4" as the observation target, you can see that the root node "4" remains unchanged, its left child "2" and right child "7" have swapped positions, and the left child "2" is located The left subtree and the right subtree where the right child "7" is located have also exchanged positions as a whole. The same rule also exists in other nodes.
So we came to the conclusion,

The operation of flipping the binary tree includes:
(1) The root node remains unchanged;
(2) The left subtree and the right subtree are swapped.
(3) Flip the left subtree;
(4) Flip the right subtree.

4. Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    public TreeNode invertTree(TreeNode root)
    {
    
    
    	// 递归的终止条件
        if(root == null)
            return root;
        // 根非空的话,交换左右子树
        TreeNode cache = root.left;
        root.left = root.right;
        root.right = cache;
        // 翻转左子树
        invertTree(root.left);
        // 翻转右子树
        invertTree(root.right);
        return root;
    }
}

5. Verification

Insert picture description here

6. Source

  1. LeetCode 226. Invert Binary Tree
    Source: LeetCode
    Link: https://leetcode-cn.com/problems/invert-binary-tree
    Copyright is owned by LeetCode Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/PursueLuo/article/details/108630077