leetcode Symmetric Tree(*)

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

For example, this binary tree is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following is not:

    1
   / \
  2   2
   \   \
   3    3

Note:

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

      判断树本身是否自己的镜像树,即是否为中轴对称树。递归的思想很简单,保存树的左右节点,对于当前的两个节点,判断值是否相同,同时判断当前两个节点对称的 左右 和 右左 孩子是否相同,分辨以左右 右左孩子为当前节点进行递归。

class Solution {
public:
    bool isSymmetricRec(TreeNode *lRoot,TreeNode *rRoot){
        if(lRoot==NULL&&rRoot==NULL)return true;
        if(lRoot==NULL||rRoot==NULL)return false;
        return lRoot->val==rRoot->val&&isSymmetricRec(lRoot->left,rRoot->right)&&isSymmetricRec(lRoot->right,rRoot->left);
    }
    bool isSymmetric(TreeNode *root) {
        if(root==NULL)return true;
        return isSymmetricRec(root->left,root->right);
    }
};
      对于迭代,一层一层的遍历比较,设前一层为ver[pre],存储的前一层的成对的相同的节点,设当前层为ver[cur],则由pre层生成cur层。这里存储的形式为对称的一对一对的节点,故数组的遍历步长为2.

class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        if(root==NULL)return true;
        vector<TreeNode*> ver[2];
        int pre=1,cur=0;
        if(root->left==NULL&&root->right==NULL)return true;
        else if(root->left==NULL||root->right==NULL)return false;
        else if(root->left->val!=root->right->val)return false;
        ver[cur].push_back(root->left);ver[cur].push_back(root->right);
        while(ver[cur].size()>0){
            cur=!cur;
            pre=!pre;
            ver[cur].clear();
            for(int i=0;i<ver[pre].size();i+=2){
                if(ver[pre][i]->left==NULL&&ver[pre][i+1]->right==NULL);
                else if(ver[pre][i]->left==NULL||ver[pre][i+1]->right==NULL)return false;
                else if(ver[pre][i]->left->val!=ver[pre][i+1]->right->val)return false;
                else{
                    ver[cur].push_back(ver[pre][i]->left);ver[cur].push_back(ver[pre][i+1]->right);
                }
                if(ver[pre][i]->right==NULL&&ver[pre][i+1]->left==NULL);
                else if(ver[pre][i]->right==NULL||ver[pre][i+1]->left==NULL)return false;
                else if(ver[pre][i]->right->val!=ver[pre][i+1]->left->val)return false;
                else{
                    ver[cur].push_back(ver[pre][i]->right);ver[cur].push_back(ver[pre][i+1]->left);
                }
            }
        }
        return true;
    }
};

你可能感兴趣的:(LeetCode)