leetcode 101 Symmetric Tree

判定两棵树是否严格镜像对称。

解决:

BFS

bool isSymmetric(TreeNode* root) {
    if (root == NULL)
        return true;
    deque<TreeNode*> now;
    now.push_back(root->left);
    now.push_back(root->right);
    
    while (now.size() > 0) {
        int size = now.size();
        for (int i = 0; i < size / 2; ++i) {
            int left = now[i]?now[i]->val:NULL;
            int right = now[size - i - 1]?now[size - i - 1]->val:NULL;
            if (left != right)
                return false;
        }
        for (int i = 0; i < size; ++i) {
            TreeNode* n = now.front();
            now.pop_front();
            if (n) {
                now.push_back(n->left);
                now.push_back(n->right);
            }
        }
    }
    return true;
}

DFS

bool isSymmetric(TreeNode* root) {
    if(root==NULL)
        return true;
    return dfs(root->left,root->right);
    
}

bool dfs(TreeNode *left, TreeNode* right){
    if(left==NULL || right ==NULL)
        return left==right;

    return (left->val==right->val) && dfs(left->left,right->right) && dfs(left->right,right->left);
    
}

 

posted on 2018-01-24 00:30  willaty  阅读(100)  评论(0编辑  收藏  举报

导航