天天看點

LeetCode:101. Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this 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:

1
   / \
  2   2
   \   \
   3    3
      

Note:

Bonus points if you could solve it both recursively and iteratively.

做了這麼多的題目,發覺樹的問題都可以用遞歸解決,可是我一直沒有勇氣用非遞歸的方法解決樹的問題,因為自己真的對堆棧不太熟悉。這道題也是遞歸,判斷是否是對稱樹。

AC:

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