LeetCode | 101. Symmetric Binary Tree

LeetCode | 101. Symmetric Binary Tree

OJ link

Insert image description here

  • It is difficult to make a judgment in this function. We define another function to
  • If both are equal and empty, return true
  • One is empty, one is not empty
  • If both are not empty, compare the values.
  • Then recurse the left of 1, the right of 2, the right of 1, and the left of 2
bool _isSymmetric(struct TreeNode* root1,struct TreeNode* root2)
{
    
    
    //如果两个都相等为空,就返回true
    if(root1 == NULL && root2 == NULL)
        return true;
    
    //一个为空,一个不为空
    if(root1 == NULL || root2 == NULL)
        return false;
    
    //都不为空,就比较值
    if(root1->val != root2->val)
        return false;

    //遍历root1的左和2右
    //1的右和2的左
    return _isSymmetric(root1->left,root2->right)
        && _isSymmetric(root1->right,root2->left);
}


bool isSymmetric(struct TreeNode* root) {
    
    
    return _isSymmetric(root->left,root->right);
}

Guess you like

Origin blog.csdn.net/2201_76004325/article/details/134767557