[leetcode刷题系列]Symmetric Tree

来源:互联网 发布:黄金时时彩缩水软件 编辑:程序博客网 时间:2024/04/30 13:39

- - 递归版本先


/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {    bool isSy(TreeNode * left, TreeNode * right){        if(left == 0 && right == 0)            return true;        if(left == 0 || right == 0)            return false;        if(left->val != right->val)            return false;        return isSy(left->left, right->right) && isSy(left->right, right->left);    }public:    bool isSymmetric(TreeNode *root) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(root == 0)            return true;        if(root->left == 0 && root->right == 0)            return true;        return isSy(root->left, root->right);    }};


非递归版本, 通过判断每一层是否回文来判断

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {    bool ispl(vector<TreeNode* > & vc){        int left = 0, right = vc.size() - 1;        while(left < right){            if(vc[left] == 0 && vc[right] == 0)                ;            else if(vc[left] == 0 || vc[right] == 0)                return false;            else if(vc[left]->val != vc[right]->val)                return false;            ++ left;            -- right;        }        return true;    }public:    bool isSymmetric(TreeNode *root) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(root == 0)            return true;        int pre = 0, next = 1;        vector<TreeNode* > vc[2];        vc[0].push_back(root);        while(vc[pre].size() > 0){            for(int i = 0; i < vc[pre].size(); ++ i){                TreeNode * now = vc[pre][i];                if(now != 0){                    vc[next].push_back(now->left);                    vc[next].push_back(now->right);                }            }            vc[pre].clear();            if(!ispl(vc[next]))                return false;            swap(pre, next);        }        return true;    }};