算法作业HW17:LeetCode101 Symmetric Tree
来源:互联网 发布:淘宝虚拟充值网店 编辑:程序博客网 时间:2024/06/08 17:56
Description:
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:
Note:
1 / \ 2 2 / \ / \3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / \ 2 2 \ \ 3 3Bonus points if you could solve it both recursively and iteratively
Solution:
Analysis and Thinking:
给定要求在一棵二叉树作为输入的情况下,检查它是否是它自身的轴对称的镜像。这题比较简单,只需要看图做题,利用递归的方法就可以解决,一开始递归左右子树,当满足以下条件:第一棵树的右子树与第二棵树的左子树相同且第二棵树的右子树与第一棵树的左子树也完全相同时,我们就说该树满足对称条件,是轴对称的镜像
Steps:
1.判断根节点是否为空,若为空,返回true
2.如果左右节点都不为空,进入递归,递归过程中,当出现任意一次当前两节点值不相等,则返回false
3.直到递归至叶子节点,则其左右子树为空,递归返回true,为正确结果
Codes:
/** * 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 isMinor(root->left,root->right); if(root->left==NULL&&root->right==NULL) return true; return false; } private: bool isMinor(TreeNode* x,TreeNode* y){ if(x==NULL&&y==NULL) return true; if(x!=NULL&&y!=NULL){ if(x->val!=y->val) return false; else if(x->left==NULL&&x->right==NULL&&y->left==NULL&&y->right==NULL) return true; else{ if(isMinor(x->left,y->right)&&isMinor(x->right,y->left)) return true; } } return false; } };
Results:
阅读全文
0 0
- 算法作业HW17:LeetCode101 Symmetric Tree
- LeetCode101—Symmetric Tree
- LeetCode101 Symmetric Tree
- LeetCode101. Symmetric Tree
- leetcode101~Symmetric Tree
- leetcode101 Symmetric Tree
- LeetCode101. Symmetric Tree题解
- LeetCode101 Symmetric Tree
- LeetCode101. Symmetric Tree
- leetcode101. Symmetric Tree
- LeetCode101. Symmetric Tree
- LeetCode101. Symmetric Tree
- LeetCode101——Symmetric Tree
- Symmetric Tree算法详解
- LeetCode算法题目:Symmetric Tree
- 101. Symmetric Tree 对称树,递归算法
- 15算法课程 101. Symmetric Tree
- Symmetric Tree
- Opencv学习之分水岭算法
- caffe计算图片数据的均值详解
- TaskStackBuilder$SupportParentable cannot be resolved. It is indirectly referenced from required .cl
- 现主流AR各大SDK功能优缺点
- tensorflow版本更新
- 算法作业HW17:LeetCode101 Symmetric Tree
- 【PB】配置外源数据库(以SQL Server为例)
- 配置CORS解决跨域调用—反思思考问题的方式
- 谈谈对OS中的中间虚拟层的看法
- Struts网站基于Filter的XSS漏洞修复
- [leetcode]45. Jump Game II(Java)
- P1066 2^k进制数 NOIP 2006 提高组 第四题
- android桌面小部件appwidget使用ListView或者StackView如何刷新
- 响应式设计(responsive web design)的视图显示法