LeetCode解题报告 101. Symmetric Tree [easy]
来源:互联网 发布:ubuntu下配置snmp环境 编辑:程序博客网 时间:2024/06/04 08:19
题目描述
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
解题思路
题目很好理解,判断二叉树是否镜面对称。
用递归的方法来解,BFS。首先判断跟结点左右子树的情况,若同时为空则返回true,程序中止;若一个为空,返回false,程序中止;若同时为相同的顶点值,则继续判断两个结点各自的左右子树,若对称则1左等于2右且1右等于2左,不断递归下去。
复杂度分析
我们遍历整个输入树一次,因此时间复杂度是O(n),其中n是树中的节点总数。
递归调用的数量受到树的高度的约束。 在最坏的情况下,树是线性的,高度在O(n)。 因此,在最坏的情况下,由于对堆栈的递归调用而导致的空间复杂度为O(n)。
递归调用的数量受到树的高度的约束。 在最坏的情况下,树是线性的,高度在O(n)。 因此,在最坏的情况下,由于对堆栈的递归调用而导致的空间复杂度为O(n)。
代码如下:
/** * 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; return isSymmetric2(root->left, root->right); } bool isSymmetric2(TreeNode *l, TreeNode *r){ if (l==NULL&&r==NULL) { return true; } if (l==NULL&&r!=NULL) { return false; } if (l!=NULL&&r==NULL) { return false; } if (l->val!=r->val) { return false; } if (!isSymmetric2(l->left, r->right)) { return false; } if (!isSymmetric2(l->right, r->left)) { return false; } return true; }};
0 0
- LeetCode解题报告 101. Symmetric Tree [easy]
- [leetcode] 101. Symmetric Tree 解题报告
- 【LeetCode】101. Symmetric Tree 解题报告
- [Leetcode] 101. Symmetric Tree 解题报告
- [leetcode]101. Symmetric Tree@Java解题报告
- [LeetCode] Symmetric Tree 解题报告
- 【LeetCode】Symmetric Tree 解题报告
- Leetcode 101. Symmetric Tree 验证树的对称性 解题报告
- LeetCode(101) Symmetric Tree解题报告
- LeetCode解题报告 100. Same Tree [easy]
- 【LeetCode】100.Same Tree(Easy)解题报告
- Leetcode 101. Symmetric Tree (Easy) (cpp)
- leetcode-101. Symmetric Tree 解题笔记
- [Leetcode 101, Easy] Symmetric Tree
- LeetCode #101 - Symmetric Tree - Easy
- 【Leetcode-Easy-101】 Symmetric Tree
- LeetCode解题报告 104. Maximum Depth of Binary Tree [easy]
- LeetCode解题报告 102. Binary Tree Level Order Traversal [easy]
- Android5.x自定义水波效果
- oracle删除链接
- What is meant by Asymmetrical protocols?
- android 单例模式
- Shell获取毫秒时间
- LeetCode解题报告 101. Symmetric Tree [easy]
- 【Bash百宝箱】gdb命令
- RSS是什么,RSS怎么玩,RSS原理是什么
- JAVA从菜鸟【入门】到新手【实习】一一一一Python 内置函数,标准库与第三方库(拓展库),常用框架
- Android自定义无限加载条-彩虹
- java_eclipse_ecj编译出错
- js事件委托和文档碎片
- HTTPS单向认证&双向认证
- php include 和require的区别