LeetCode解题报告 101. Symmetric Tree [easy]
2016-10-13 13:30
337 查看
题目描述
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)。
代码如下:
/** * 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; } };
相关文章推荐
- 【LeetCode】111.Minimum Depth of Binary Tree(Easy)解题报告
- 【LeetCode】637.Average of Levels in Binary Tree(Easy)解题报告
- [leetcode] 101. Symmetric Tree 解题报告
- LeetCode解题报告 104. Maximum Depth of Binary Tree [easy]
- 【LeetCode】104.Maximum Depth of Binary Tree(Easy)解题报告
- 【LeetCode】100.Same Tree(Easy)解题报告
- 【LeetCode】572.Subtree of Another Tree(Easy)解题报告
- LeetCode解题报告 100. Same Tree [easy]
- LeetCode】101.Symmetric Tree(Easy)解题报告
- 【LeetCode】108.Convert Sorted Array to Binary Search Tree(Easy)解题报告
- 【LeetCode】226.Invert Binary Tree(Easy)解题报告
- 【LeetCode】270.Closest Binary Search Tree Value(Easy)解题报告
- LeetCode解题报告 110. Balanced Binary Tree [easy]
- [Leetcode] 101. Symmetric Tree 解题报告
- LeetCode解题报告 257. Binary Tree Paths [easy]
- 【LeetCode】235.Lowest Common Ancestor of a Binary Search Tree(Easy)解题报告
- 【LeetCode】110. Balanced Binary Tree(Easy)解题报告
- LeetCode解题报告 111. Minimum Depth of Binary Tree [easy]
- LeetCode 257. Binary Tree Paths 解题报告
- LeetCode Binary Tree Maximum Path Sum 解题报告