Symmetric Tree
来源:互联网 发布:淘宝查询 编辑:程序博客网 时间:2024/04/30 04:04
Symmetric Tree
题记:为了明年的各种笔试面试,现在开始,计划每两天在LeetCode里面AC一个算法题,目前里面有150多个,差不多明年8,9月份能做完,给自己的动力吧。
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
题目要求尽量用递归、迭代,暂时使用了层次遍历的方式,使用两个队列来保存要比较的各个节点。
bool isSymmetric(TreeNode *root) {if(root == NULL){return true;}TreeNode* pLeft=root->left, *pRight=root->right;//把节点集从根节点分开,将根节点的左子树节点保存到qLeft中,右子树节点保存到qRight中queue<TreeNode*> qLeft, qRight;qLeft.push(pLeft);qRight.push(pRight);//两个队列都不空,层次遍历算法,一层一层对两个队列的元素进行比较while(qLeft.empty()==false && qRight.empty()==false){pLeft = qLeft.front();pRight = qRight.front();if(pLeft!=NULL && pRight!=NULL){if(pLeft->val != pRight->val){return false;}else{qLeft.pop();//先入该节点的左子节点,再入右子节点qLeft.push(pLeft->left);qLeft.push(pLeft->right);qRight.pop();//先入该节点的右子节点,再入左子节点qRight.push(pRight->right);qRight.push(pRight->left);}}else if(pLeft==NULL && pRight==NULL){qLeft.pop();qRight.pop();}else{return false;}}if(qLeft.empty()==true && qRight.empty()==true){return true;}else{return false;}}
后续递归、迭代算法再进行补充。。。
题目链接:https://oj.leetcode.com/problems/symmetric-tree/
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
- 我在家里过冬天吗
- Saliency Detection on Light Field
- 的设计费离开家萨连科
- iOS8 WebKit库之——WKWebView篇
- 隔阂二工大放个假回复如图仿古街
- Symmetric Tree
- 大数乘法
- java使用链表实现排序
- Linux chmod +755
- 关于MyEclipse Professional 2014安装jad反编译插件不起作用原因
- yum卡在Running Transaction Test
- JAVA支持---出栈后的元素
- 冬天到了
- C++函数的导出与导入