[Simple Algorithm] 28. Symmetric Binary Tree

topic:

Given a binary tree, check if it is mirror symmetric.

For example, a binary tree [ 1 , 2 , 2 , 3 , 4 , 4 , 3 ] is symmetric.

    1 
   / \
   2    2 
 / \ / \
 3   4  4   3 
but the following [ 1 , 2 , 2 , null , 3 , null , 3 ] is not mirror-symmetric:

    1
   / \
  2   2
   \   \
   3    3
illustrate:

Bonus points if you can solve this problem using both recursion and iteration.

Problem solving ideas:

recursion

1. Determine whether the value of the left child is equal to the value of the right child, and at the same time determine whether both the left subtree and the right subtree are mirror trees.

Source code:

/**
 * 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 isSymmetricTree(TreeNode* root1,TreeNode* root2){
        if((root1&&!root2)||(!root1&&root2)){
            return false;
        }
        
        if(root1 == NULL && root2 == NULL){
            return true;
        }
        
        if(root1->val != root2->val){
            return false;
        }
        
        return isSymmetricTree(root1->left,root2->right)&&isSymmetricTree(root1->right,root2->left);
    }
    
    bool isSymmetric(TreeNode* root) {
        if(root == NULL){
            return true;
        }
        
        return isSymmetricTree(root->left,root->right);
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325286174&siteId=291194637