LeetCode 101. Symmetric Tree

来源:互联网 发布:淘宝店铺装修模块代码 编辑:程序博客网 时间:2024/06/05 21:09

LeetCode 101. Symmetric Tree

Description:

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

Example 1:

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

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

Example 2:

But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3


分析:

其实这道题可以参考LeetCode 100. Same Tree类似的解法,首先我们判断树的根节点,然后把左右子树看成和Same Tree一样求两棵树是否一样,只不过此时p->left==r->left换成p->left==r->right,p->right==r->right换成p->right==r->left。

这道题最麻烦的还是写main函数测试样例时构造二叉树的问题,又提醒我要复习一下数据结构的知识,最终我找了两个构造二叉树的方法,两个版本的代码在底下都可以看到;
另外我还把LeetCode.com上面自带的测试main函数放在这个博客里,人家的代码写得就是吊,用到了很多标准库函数,把样例作为字符串输入,然后处理字符串构造二叉树。666


代码如下:
one version:

#include <iostream>#include <malloc.h>using namespace std;/** * 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;        return isMirror(root->left, root->right);    }    bool isMirror(TreeNode* p, TreeNode* q) {        if (p == NULL && q == NULL) return true;        else if (p != NULL && q != NULL && p->val == q->val && isMirror(p->left, q->right) && isMirror(p->right, q->left))            return true;        else return false;    }};// 构造二叉树void TreeNodeCreate(TreeNode **tp) {    // 构造方法,或者说构造顺序:从左子树开始构造    int x;    cin >> x;    if(x < 0) {        *tp = NULL;// 指针为空,树节点中的某个指针为空        return;    }    *tp = (TreeNode*)malloc(sizeof(TreeNode));// 将树节点中指针指向该地址空间    if(tp == NULL) return;    (*tp)->val =x;    TreeNodeCreate(&((*tp)->left));    TreeNodeCreate(&((*tp)->right));}int main() {    Solution s;    TreeNode* tree;    TreeNodeCreate(&tree);    cout << s.isSymmetric(tree) << endl;    return 0;}/*input:123-1 -14-1 -124-1 -13-1 -1output:1 *//*input:12-13-1 -12-1 3-1 -1output:0 */

another version:

#include <iostream>#include <malloc.h>using namespace std;/** * 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;        return isMirror(root->left, root->right);    }    bool isMirror(TreeNode* p, TreeNode* q) {        if (p == NULL && q == NULL) return true;        else if (p != NULL && q != NULL && p->val == q->val && isMirror(p->left, q->right) && isMirror(p->right, q->left))            return true;        else return false;    }};// 构造二叉树int TreeNodeCreate(TreeNode* &tree) {    int val;    cin >> val;    if (val < 0) // 小于0表示空节点        tree = NULL;    else {        tree = new TreeNode(val); // 创建根节点        tree->val = val;        TreeNodeCreate(tree->left); // 创建左子树        TreeNodeCreate(tree->right);// 创建右子树    }    return 0;}int main() {    Solution s;    TreeNode* tree;    TreeNodeCreate(tree);    cout << s.isSymmetric(tree) << endl;    return 0;}/*input:123-1 -14-1 -124-1 -13-1 -1output:1 *//*input:12-13-1 -12-1 3-1 -1output:0 */

one more version from LeetCode.com:

#include <iostream>#include <sstream>#include <algorithm>#include <string>#include <queue>using namespace std;/** * 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;        return isMirror(root->left, root->right);    }    bool isMirror(TreeNode* p, TreeNode* q) {        if (p == NULL && q == NULL) return true;        else if (p != NULL && q != NULL && p->val == q->val && isMirror(p->left, q->right) && isMirror(p->right, q->left))            return true;        else return false;    }};void trimLeftTrailingSpaces(string &input) {    input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {        return !isspace(ch);    }));}void trimRightTrailingSpaces(string &input) {    input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {        return !isspace(ch);    }).base(), input.end());}TreeNode* stringToTreeNode(string input) {    trimLeftTrailingSpaces(input);    trimRightTrailingSpaces(input);    input = input.substr(1, input.length() - 2);    if (!input.size()) {        return nullptr;    }    string item;    stringstream ss;    ss.str(input);    getline(ss, item, ',');    TreeNode* root = new TreeNode(stoi(item));    queue<TreeNode*> nodeQueue;    nodeQueue.push(root);    while (true) {        TreeNode* node = nodeQueue.front();        nodeQueue.pop();        if (!getline(ss, item, ',')) {            break;        }        trimLeftTrailingSpaces(item);        if (item != "null") {            int leftNumber = stoi(item);            node->left = new TreeNode(leftNumber);            nodeQueue.push(node->left);        }        if (!getline(ss, item, ',')) {            break;        }        trimLeftTrailingSpaces(item);        if (item != "null") {            int rightNumber = stoi(item);            node->right = new TreeNode(rightNumber);            nodeQueue.push(node->right);        }    }    return root;}string boolToString(bool input) {    return input ? "True" : "False";}int main() {    string line;    while (getline(cin, line)) {        TreeNode* root = stringToTreeNode(line);        bool ret = Solution().isSymmetric(root);        string out = boolToString(ret);        cout << out << endl;    }    return 0;}// this one is from LeetCode.com/*input:[1,2,2,3,4,4,3]output:True *//*input:[1,2,2,null,3,null,3]output:False */