Symmetric Tree
来源:互联网 发布:单片机键盘输入 编辑:程序博客网 时间:2024/05/17 23:40
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:
1 / \ 2 2 / \ / \3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
Subscribe to see which companies asked this question
题目:观察一棵树是不是对称的二叉树。
思想:利用递归依次判断,新写一个函数用来传递对称的结点即可,代码:
/**
* 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) return true;
return isSymmetric(root->left,root->right);
}
bool isSymmetric(TreeNode* leftCode,TreeNode* rightCode){
if(!leftCode && !rightCode) return true;
if(leftCode && !rightCode ||
rightCode && !leftCode ||
leftCode->val != rightCode->val)
return false;
return isSymmetric(leftCode->left,rightCode->right) && isSymmetric(leftCode->right,rightCode->left);
}
};
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- SQL server 2008不允许保存更改的解决办法
- jsonp跨域
- java并发编程之synchronized
- 我的第一次
- 编译u-boot-2009.1.1.cnxt
- Symmetric Tree
- 【bzoj4198】[NOI2015]荷马史诗
- CoreData数据验证失败仍然插入context的解决(三)
- .NET MVC实现多图片上传并附带参数(ajaxfileupload)
- LINQ可视化查询编辑器: VLinq
- asp.net mvc 中验证码
- Android graphic 架构
- 学习LINQ工具:LINQPad
- 【bzoj1067】[SCOI2007]降雨量