leetcode刷题,总结,记录,备忘 101

来源:互联网 发布:java纽约大亨 编辑:程序博客网 时间:2024/06/07 17:47

leetcode101

Symmetric Tree

 

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

For example, this binary tree is symmetric:

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

But the following is not:

    1   / \  2   2   \   \   3    3

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

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

递归实现,左子树的左子树与右子树的右子树相同,依次类似,即可。

/** * 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 is(TreeNode * left, TreeNode * right)    {        if (left == NULL && right == NULL)        return true;        if (left == NULL && right != NULL)        return false;        if (left != NULL && right == NULL)        return false;        if (left->val != right->val)        return false;                return is(left->left, right->right) && is(left->right, right->left);    }        bool isSymmetric(TreeNode* root) {        if (root == NULL)        return true;        if (root->left == NULL && root->right == NULL)        return true;        return is(root->left, root->right);    }};



0 0
原创粉丝点击