当前位置:网站首页>Sword finger offer 28 Symmetric binary tree

Sword finger offer 28 Symmetric binary tree

2022-07-07 22:52:00 Yes' level training strategy

subject : Please implement a function , Used to judge whether a binary tree is symmetrical . If a binary tree is the same as its mirror image , So it's symmetrical .

for example , Binary tree [1,2,2,3,4,4,3] It's symmetrical .

But the next one [1,2,2,null,3,null,3] It's not mirror symmetric :

Example 1:

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

Output :true

Example 2:

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

Output :false

According to the meaning , In fact, it is to compare the left and right subtrees .

First judge the root node's left Whether or not right equal , If so, continue recursive judgment , The objects of judgment are left.left and right.right、left.right and right.left.

In this way, recursive judgment in turn , The idea should be very clear , If you encounter any nonconformity in the middle, you can return directly .

Let's take a look at the code :

class Solution {
    
    public boolean isSymmetric(TreeNode root) {
    
        if (root == null) {
    
            return true;
        }
        return isSymmetric(root.left, root.right);
    }   
    private boolean isSymmetric(TreeNode left, TreeNode right) {
    
        if ((left == null && right != null) || (left != null && right == null)) {
    
            return false;
        }
        if (left == null && right == null) {
    
            return true;
        }
        if (left.val != right.val) {
    
            return false;
        }
        return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
    }  
}

This is the most obvious and direct judgment , therefore isSymmetric The code can be optimized :

class Solution {
    

    private boolean isSymmetric(TreeNode left, TreeNode right) {
    
        if (left == null && right == null) {
    
            return true;
        }
        if (left == null || right == null || left.val != right.val) {
    
            return false;
        }
        return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
    }  
}

Time complexity O(N), Spatial complexity O(N)


Okay , A simple question !

https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof/

原网站

版权声明
本文为[Yes' level training strategy]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130602332699.html