leetcode No101. Symmetric Tree
来源:互联网 发布:linux 查看显卡型号 编辑:程序博客网 时间:2024/06/05 02:53
Question:
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
判断二叉树是否左右对称
Algorithm:
对左右子树BFS(宽度优先搜索),要注意判断左右子树一个非空一个不为空的情况
Accepted Code:
/** * 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; queue<TreeNode*> l; //左子树 queue<TreeNode*> r; //右子树 if(root->left==NULL&&root->right==NULL) return true; else if(root->left!=NULL&&root->right!=NULL) { l.push(root->left); r.push(root->right); } else return false; while(!l.empty()&&!r.empty()) { TreeNode* temp1=l.front(); TreeNode* temp2=r.front(); if(temp1->val!=temp2->val) return false; l.pop(); r.pop(); if(temp1->left&&temp2->right) { l.push(temp1->left); r.push(temp2->right); } else if((temp1->left==NULL^temp2->right==NULL)==1) return false; if(temp1->right&&temp2->left) { l.push(temp1->right); r.push(temp2->left); } else if((temp1->right==NULL^temp2->left==NULL)==1) return false; } if(l.empty()&&r.empty()) return true; else return false; }};
0 0
- leetcode No101. Symmetric Tree
- 【LeetCode从零单排】No100 Same Tree && No101 Symmetric Tree
- Leetcode - Tree - Symmetric Tree
- Leetcode - Tree - Symmetric Tree
- LeetCode[Tree]: Symmetric Tree
- [leetcode][tree] Symmetric Tree
- LeetCode: Symmetric Tree
- [Leetcode] Symmetric Tree
- LeetCode : Symmetric Tree
- leetcode 13:symmetric tree
- [LeetCode] Symmetric Tree - Recursively
- [LeetCode] Symmetric Tree - Iteratively
- [LeetCode] Symmetric Tree
- [LeetCode]Symmetric Tree
- Leetcode:Symmetric Tree
- [Leetcode]Symmetric Tree
- Leetcode: Symmetric Tree
- [leetcode]Symmetric Tree
- 嵌套控件的可见关系记录
- alsa lib和utils交叉编译与移植
- 让网页中图片无法拖动
- CSS鼠标样式
- BitMap,inputStream,byte[],Drawable之间的相互转换
- leetcode No101. Symmetric Tree
- UILabel的有关用法
- Genymotion 安装项目失败,闪退
- DispatcherServlet的认识和解析
- 问题 T 序列求和
- sql语句CASE WHEN 的使用
- LintCode_393 Best Time to Buy and Sell Stock IV
- [ios]启动 EASession 失败 — — EAAccessory 没有Protocol
- excel去重复