Symmetric Tree

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

解决了same tree这个问题,这个问题就迎刃而解了。


class Solution {
public:
  bool isSameTree(TreeNode *p, TreeNode *q) {  
        if(p && q && p->val == q->val)  
        {  
            bool b = isSameTree(p->left, q->right);  
            if(b == false) return false;  
            return isSameTree(p->right, q->left);  
        }  
        if(q == NULL && p == NULL)  
        return true;  
        else return false;  
    } 
    bool isSymmetric(TreeNode *root) {
        if(root == NULL || root->left == NULL && root->right == NULL)
        return true;
        return isSameTree(root->left, root->right);
    }
};


你可能感兴趣的:(Algorithm,C++,递归,tree)