标签:style blog http color io strong ar for div
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.
实质是判断两颗树相同的变形,要判断一颗数是否对称,那么就是判断他的两颗子树是否对称相等,代码如下:
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isSymmetric(TreeNode *root) { 13 if( !root ) return true; 14 return isSyRec(root->left, root->right); 15 } 16 17 bool isSyRec(TreeNode* lhs, TreeNode* rhs) { 18 if( !lhs && !rhs ) return true; 19 if( lhs && rhs && lhs->val == rhs->val ) //lhs左子树与rhs右子树相同,lhs右子树与rhs左子树相同 20 return isSyRec(lhs->left, rhs->right) && isSyRec(lhs->right, rhs->left); 21 return false; 22 } 23 };
标签:style blog http color io strong ar for div
原文地址:http://www.cnblogs.com/bugfly/p/3942301.html