Symmetric binary tree judgment

topic

Symmetric binary tree judgment

Topic requirements

insert image description here
topic link

example

answer

method one,

recursive method

Implementation ideas

The method of judging whether two binary trees are equal is used, but the symmetric binary tree judges whether the left child of p node and the right child of q node, the right child of p node and the left child of q node are equal.

Time Complexity and Space Complexity

Time complexity: O(N)
Space complexity: O(N)

the code

 bool isSameTree(struct TreeNode* p, struct TreeNode* q){
    
    
    if(p==NULL&&q==NULL)
    {
    
    
        return true;
    }
    if(p==NULL||q==NULL)
    {
    
    
        return false;
    }
    if(p->val!=q->val)
    {
    
    
        return false;
    }
    //和判断两个二叉树相等类似,不过判断的是p结点的左孩子和q结点的右孩子是否相等
    //还判断p结点的右孩子和q结点的左孩子是否相等,因为对称为镜像,所以需要这样比较。
    return isSameTree(p->left,q->right)&&isSameTree(p->right,q->left);
 }
bool isSymmetric(struct TreeNode* root){
    
    
    //如果二叉树为空,则返回true
    if(root==NULL)
    {
    
    
        return true;
    }

    return isSameTree(root->left,root->right);
}

Method Two,

Implementation ideas

Time Complexity and Space Complexity

the code


Guess you like

Origin blog.csdn.net/dong132697/article/details/132585348