leetcode-Symmetric Tree 对称树
2015-06-09 09:51
399 查看
class Solution {
public:
vector<int>result;
int l;
bool isSymmetric(TreeNode* root) {
int i,j;
if(root == NULL) return true;
inorder(root);
l=result.size();
for(i=0,j=l-1;i<j;i++,j--)
{
if(result[i]!=result[j])
return false;
}
return true;
}
void inorder(TreeNode* root)
{
if(root==NULL) return;
inorder(root->left);
// if(root->left!=NULL)
result.push_back(root->val);
// if(root->right!=NULL)
inorder(root->right);
}
};
中序遍历,结果不对
递归
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root) return true;
else return symmetric(root->left,root->right);
}
bool symmetric(TreeNode* t1,TreeNode* t2)
{
if(!t1&&!t2) return true;
if(!t2&&t1) return false;
if(!t1&&t2) return false;
if(t1->val!=t2->val) return false;
else return symmetric(t1->left,t2->right)&&symmetric(t1->right,t2->left);
}
};
非递归
class Solution {
public:
bool isSymmetric (TreeNode* root) {
if (!root) return true;
stack<TreeNode*> s;
s.push(root->left);
s.push(root->right);
while (!s.empty ()) {
auto p = s.top (); s.pop();
auto q = s.top (); s.pop();
if (!p && !q) continue;
if (!p || !q) return false;
if (p->val != q->val) return false;
s.push(p->left);
s.push(q->right);
s.push(p->right);
s.push(q->left);
}
return true;
}
};
public:
vector<int>result;
int l;
bool isSymmetric(TreeNode* root) {
int i,j;
if(root == NULL) return true;
inorder(root);
l=result.size();
for(i=0,j=l-1;i<j;i++,j--)
{
if(result[i]!=result[j])
return false;
}
return true;
}
void inorder(TreeNode* root)
{
if(root==NULL) return;
inorder(root->left);
// if(root->left!=NULL)
result.push_back(root->val);
// if(root->right!=NULL)
inorder(root->right);
}
};
中序遍历,结果不对
递归
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root) return true;
else return symmetric(root->left,root->right);
}
bool symmetric(TreeNode* t1,TreeNode* t2)
{
if(!t1&&!t2) return true;
if(!t2&&t1) return false;
if(!t1&&t2) return false;
if(t1->val!=t2->val) return false;
else return symmetric(t1->left,t2->right)&&symmetric(t1->right,t2->left);
}
};
非递归
class Solution {
public:
bool isSymmetric (TreeNode* root) {
if (!root) return true;
stack<TreeNode*> s;
s.push(root->left);
s.push(root->right);
while (!s.empty ()) {
auto p = s.top (); s.pop();
auto q = s.top (); s.pop();
if (!p && !q) continue;
if (!p || !q) return false;
if (p->val != q->val) return false;
s.push(p->left);
s.push(q->right);
s.push(p->right);
s.push(q->left);
}
return true;
}
};
相关文章推荐
- Linux学习之库函数方式文件编程
- 煤火车问题
- 微信JS接口汇总及使用详解(转)
- QT5安装(null)
- 获取jqGrid中每行的子元素td并修改其属性
- 【点滴】LINUX之字符串截取
- Web 研发模式演变
- 《敦煌》—— 读后总结
- <a href="javascript:;" ></a>
- 14.8 配置角色
- mongodb 执行js脚本(二)---mongovue执行
- 远程登录创建仓库
- 磨砂效果
- mongodb 执行js脚本(二)---mongovue执行
- 深入分析QEMU cache——虚拟机迁移需要注意writeback方式会造成数据丢失。
- android关于导入工程报错、常见问题解决
- 打造android万能上拉下拉刷新框架——XRefreshView (一)
- java基础之异常
- 那些在学习iOS开发前就应该知道的事(part 1)
- android 获取资源文件 r.drawable中的图片转换为drawable、bitmap