Symmetric Tree
2015-08-07 14:19
375 查看
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
But the following is not:
This problem can be solve by using a simple recursion. The key is finding the conditions that return false, such as value is not equal, only one node(left or right) has value.
/**
* 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 helper(TreeNode* l, TreeNode* r)
{
if(l == NULL && r == NULL)
{
return true;
}
if(l != NULL && r != NULL)
{
if(l -> val != r -> val)
{
return false;
}
return helper(l -> left, r -> right) && helper(l -> right , r -> left);
}else
{
return false;
}
}
bool isSymmetric(TreeNode* root)
{
if(root == NULL)
{
return true;
}
return helper(root -> left, root -> right);
}
};
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \3 3
This problem can be solve by using a simple recursion. The key is finding the conditions that return false, such as value is not equal, only one node(left or right) has value.
/**
* 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 helper(TreeNode* l, TreeNode* r)
{
if(l == NULL && r == NULL)
{
return true;
}
if(l != NULL && r != NULL)
{
if(l -> val != r -> val)
{
return false;
}
return helper(l -> left, r -> right) && helper(l -> right , r -> left);
}else
{
return false;
}
}
bool isSymmetric(TreeNode* root)
{
if(root == NULL)
{
return true;
}
return helper(root -> left, root -> right);
}
};
相关文章推荐
- Java动态代理实现(简单AOP实现)
- Codeforces 567 E. President and Roads
- codeforces 567D One-Dimensional Battle Ships (set)
- 新的Android databinding与android-apt plugin冲突
- 谷歌镜像
- Python学习笔记
- shutdown
- GitHub上史上最全的Android开源项目分类汇总
- Oracle创建表空间,用户,分配权限
- Hdu 2015 Multi-University Training Contest6
- eclipse从数据库逆向生成Hibernate实体类
- FileToData与DataToFile(优化版,txt为原始文件2倍大小)
- 如何运行代码apk安装
- 看懂java的class文件(字节码)(好)
- Java开发中的23种设计模式详解
- Dsploit
- Java线程的5种状态及切换(透彻讲解)
- git 和github教程
- 【cl】oracle之Sequence
- Android 实现多个输入框的对话框