101. Symmetric Tree(DFS)

1. Description

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 n

    1
   / \
  2   2
   \   \
   3    3

2. Analysis

直接的想法就是取出每一层,在该层做左右对称比较。思想与逐层遍历是类似的。时间复杂度为 O(n)


3. Algorithm achievement

/**
 * 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(root->left == NULL && root->right == NULL) return true;
    if(root->left == NULL ||  root->right == NULL) return false;

    vector<TreeNode*> tmp;
    TreeNode* node = NULL;
    tmp.push_back(root);

    while(!tmp.empty()) {
        for(int i = 0, n = tmp.size(); i < n; i++) {
            node = tmp.front();
            tmp.erase(tmp.begin());
            /*判断条件这里需要细心,有点坑*/
            if(node != NULL)  {
                tmp.push_back(node->left);
                tmp.push_back(node->right);
            }
        }

        if(tmp.size()%2 != 0) return false;

        for(int i = 0, j = tmp.size()-1; i < tmp.size()/2; i++, j--) {
            if(tmp[i] == NULL &&  tmp[j] == NULL ) continue;
            if(tmp[i] == NULL || tmp[j] == NULL ) return false;
            if(tmp[i] != NULL && tmp[j] != NULL) {
                 if((tmp[i])->val != (tmp[j])->val) 
                    return false;
            } else if(tmp[i] != NULL || tmp[j] != NULL) 
                return false;

        }
    }
    return true;
    }    

};



贴个图防坑!注意NULL结点也会参与比较的,所以需要接入向量!
这里写图片描述


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值