[] Leetcode symmetrical binary tree

 

Recursion

When execution: 12 ms, beat the 43.44% of all users to submit in C ++
Memory consumption: 14.6 MB, defeated 95.56% of all users to submit in C ++
/**
 * 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 isSymmetric(TreeNode* root) {
        if(root == NULL)
            return true;
        
        if( isMirror(root->left, root->right))
            return true;
        else
            return false;
    }
    
    bool isMirror(TreeNode* lc, TreeNode* rc) {
        if(lc == NULL && rc == NULL)
            return true;
        
        if(lc == NULL || rc == NULL)
            return false;
        else {
            if (lc->val == rc->val)
                return (isMirror(lc->left, rc->right) && isMirror(lc->right, rc->left));
            else
                return false;
        }
    }
};

time complexity:

O (n), since the process of each node algorithm to traverse the tree, the number of nodes is n.

Space complexity:

O (n), stack space used in the recursive function related to the number of layers of the tree. If the tree is a linear structure, the number of layers is n, so that the space complexity is O (n)

 

Guess you like

Origin www.cnblogs.com/gdut-gordon/p/11445061.html