首页 > 代码库 > Symmetric Tree
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.
实质是判断两颗树相同的变形,要判断一颗数是否对称,那么就是判断他的两颗子树是否对称相等,代码如下:
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 };
Symmetric Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。