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 f(TreeNode * l, TreeNode * r){
- if(l==NULL && r==NULL)
- return true;
- if(l==NULL || r==NULL)
- return false;
- return l->val==r->val && f(l->left,r->right)&&
- f(l->right,r->left);
- }
- bool isSymmetric(TreeNode *root) {
- if(root==NULL)
- return true;
- return f(root->left,root->right);
- }
<script>window._bd_share_config={"common":{"bdsnskey":{},"bdtext":"","bdmini":"2","bdminilist":false,"bdpic":"","bdstyle":"0","bdsize":"16"},"share":{}};with(document)0[(getelementsbytagname('head')[0]||body).appendchild(createelement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new date()/36e5)];</script>
阅读(7) | 评论(0) | 转发(0) |
相关热门文章
给主人留下些什么吧!~~
评论热议
本文介绍了一种通过递归方法判断二叉树是否为镜像树的算法,详细解释了如何使用两个树来进行比较,并提供了实现代码。
180

被折叠的 条评论
为什么被折叠?



