当前位置:网站首页>Leetcode-226. Invert Binary Tree

Leetcode-226. Invert Binary Tree

2022-07-07 07:30:00 Eistert

subject

Given the root of a binary tree, invert the tree, and return its root.

Example 1:

 Insert picture description here

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Example 2:

 Insert picture description here

Input: root = [2,1,3]
Output: [2,3,1]

Example 3:

Input: root = []
Output: []

Constraints:

The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100

solution

Method 1 : recursive

Ideas and algorithms

This is a classic binary tree problem . obviously , We start at the root node , Recursively traverse the tree , And start flipping from the leaf node . If the node currently traversed root The two subtrees on the left and right have been turned over , Then we just need to exchange the positions of the two subtrees , Can be completed to root Is the flip of the entire subtree of the root node .

Code

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */
class Solution {
    
    public TreeNode invertTree(TreeNode root) {
    
        if(root == null){
    
            return null;
        }
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);

        root.right = left;
        root.left = right;

        return root;
    }
}

source

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/invert-binary-tree
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

原网站

版权声明
本文为[Eistert]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130658518759.html