Symmetric Tree
来源:互联网 发布:eclipse怎么写sql语句 编辑:程序博客网 时间:2024/06/03 19:15
题目来源LeetCode
题目描述
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.
这道题用了两种方法,第一种是DFS的方法,利用队列来存储左右的值进行比较,代码如下:
/** * 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 == NULL) return true; if(root->left == NULL && root->right == NULL) return true; queue<TreeNode*>ql,qr; TreeNode*l,*r; ql.push(root->left); qr.push(root->right); l = root->left; r = root->right; while(!ql.empty() || !qr.empty() || l != NULL || r != NULL){ if((l == NULL && r != NULL)|| (l != NULL && r == NULL)) return false; else if(l != NULL && r != NULL){ if(l->val != r->val) return false; ql.push(l); qr.push(r); l = l->left; r = r->right; } else { l = ql.front()->right; r = qr.front()->left; ql.pop(); qr.pop(); } } return true; }};
第二种算法是用的递归,代码如下:
bool recursive(TreeNode*l,TreeNode*r){ if(r == NULL && l == NULL) return true; else if((r == NULL && l != NULL) || (l == NULL && r != NULL)) return false; if(l->val != r-> val) return false; else return recursive(l->left,r->right)&&recursive(l->right, r->left); }class Solution {public: bool isSymmetric(TreeNode* root) { if(root == NULL) return true; return recursive(root->left, root->right); }};
阅读全文
0 0
- 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
- Redis之一:数据结构和对象
- 图像处理之特征匹配特征提取之SIFT简单梳理
- RMI 远程方法调用
- NYOJ:22-素数求和问题
- Java 共变数组和类型擦除
- Symmetric Tree
- 跳转控制语句
- QT里使用sqlite的问题,好多坑
- Web前端知识体系精简
- Windows学习(008)--线程(二)
- js中关于无参函数、有参函数、有返回值的有参函数、匿名函数的定义
- input标签内容改变的触发事件
- python socket3 dir/cd/md指令操作 下载文件
- 闪屏页