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

Sword finger offer 28 Symmetric binary tree

2022-06-22 02:49:00 SS_ zico

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 .

    1
   / \
  2   2
 / \ / \
3  4 4  3

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

    1
   / \
  2   2
   \   \
   3    3

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

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
class Solution {
    
public:
    bool compare(TreeNode *left,TreeNode *right)
    {
    
        if(!left&&!right)return true;
        if(left == NULL || right == NULL || left->val!=right->val)return false;
        return compare(left->left,right->right)&&compare(left->right,right->left);
    }
    bool isSymmetric(TreeNode* root) {
    
        return root == NULL ? true : compare(root->left,root->right);
    }
};

Time complexity O(N) : Call at most N/2 Time compare() Method .
Spatial complexity O(N) : The worst , A binary tree degenerates into a linked list , System use O(N) The size of the stack space .

原网站

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