欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢
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 binary tree * 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 isSymmetricUtil(root->left , root->right); } bool isSymmetricUtil(TreeNode *root1 , TreeNode *root2) { if(root1==NULL || root2==NULL) return root1==NULL && root2==NULL; if(root1->val == root2->val) return isSymmetricUtil(root1->left, root2->right) && isSymmetricUtil(root1->right , root2->left); else return false; } };
//其他写法 class Solution { public: bool isSymmetricUtil(TreeNode* root1, TreeNode* root2) { if(root1 == NULL && root2 == NULL) return true; if(root1 == NULL && root2 != NULL) return false; if(root1 != NULL && root2 == NULL) return false; return root1->val == root2->val && isSymmetricUtil(root1->left, root2->right) && isSymmetricUtil(root1->right, root2->left); } bool isSymmetric(TreeNode *root) { if(root == NULL) return true; return isSymmetricUtil(root->left, root->right); } };
时间: 2024-10-10 21:42:11