2
头图

Flip binary tree

Title description: Flip a binary tree.

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/invert-binary-tree/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Recursion

Use the recursive method to flip the binary tree. The specific recursive process is as follows:

  • If the root node is null or root has no left or right child nodes, return to root directly;
  • Otherwise, first use temp to temporarily store the right subtree of root, point the right of root to the node after recursively processing the left subtree of root, and point the left of root to the node after recursively processing temp.

After the recursion is completed, the flipped binary tree is obtained.

import java.util.LinkedList;
import java.util.Queue;

public class LeetCode_226 {
    public static TreeNode invertTree(TreeNode root) {
        if (root == null || (root.left == null && root.right == null)) {
            return root;
        }
        TreeNode temp = root.right;
        root.right = invertTree(root.left);
        root.left = invertTree(temp);
        return root;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(2);
        root.right = new TreeNode(7);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(9);

        invertTree(root);
        Queue<TreeNode> nodes = new LinkedList<>();
        nodes.add(root);
        while (nodes.size() > 0) {
            TreeNode cur = nodes.poll();
            System.out.print(cur.val + " ");
            if (cur.left != null) {
                nodes.add(cur.left);
            }
            if (cur.right != null) {
                nodes.add(cur.right);
            }
        }
        for (TreeNode node : nodes) {
            System.out.print(node.val + " ");
        }
    }
}
[Daily Message] future, you will definitely thank you for your hard work now!

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!