101. Symmetric Tree

来源:互联网 发布:人体测量尺寸数据 编辑:程序博客网 时间:2024/05/18 16:55

Q

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:

这里写图片描述

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

这里写图片描述

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

A

recursively(C)

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     struct TreeNode *left; *     struct TreeNode *right; * }; */ bool judge(struct TreeNode *left, struct TreeNode *right) {     if (left == NULL && right == NULL) {         return true;     }     if (left == NULL || right == NULL) {         return false;     }     if (left->val != right->val) {         return false;     }     return (judge(left->left, right->right) && judge(left->right, right->left)); }bool isSymmetric(struct TreeNode* root) {    if (root == NULL) {        return true;    }    return judge(root->left, root->right);}

iteratively(C++)

/** * 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;        }        queue<TreeNode *> q1;        queue<TreeNode *> q2;        q1.push(root->left);        q2.push(root->right);        // 每个队列层序遍历        while (!q1.empty() && !q2.empty()) {            TreeNode *l1, *l2;            l1 = q1.front();            l2 = q2.front();            if (l1->val != l2->val) {                return false;            }            if ((l1->left==NULL&&l2->right!=NULL) || (l1->left!=NULL&&l2->right==NULL)) {                return false;            }            if ((l1->right==NULL&&l2->left!=NULL) || (l1->right!=NULL&&l2->left==NULL)) {                return false;            }            if (l1->left!=NULL && l2->right!=NULL) {                q1.push(l1->left);                q2.push(l2->right);            }            if (l1->right!=NULL && l2->left!=NULL) {                q1.push(l1->right);                q2.push(l2->left);            }            q1.pop();            q2.pop();        }        return true;    }};
0 0
原创粉丝点击