[LeetCode]--Symmetric Tree
来源:互联网 发布:公司封游戏端口 编辑:程序博客网 时间:2024/05/17 03:55
题目
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
Note:
Bonus points if you could solve it both recursively and iteratively.
中文题意:给定一棵二叉树,判断其是否关于中心轴线对称。
分析
判断一棵二叉树是否为对称的,我们必须遍历此二叉树,此题选择深度优先遍历,即首先访问出发点v,并将其标记为已访问过;然后依次从v触发搜索v的每个邻接点w。若w未被访问,则以w为新的出发点继续进行深度优先遍历,直到所有与v相通路径上的节点都被访问过为止。
此题中,我们通过对二叉树的左子树和右子树执行函数isMirrorTree,判断其是否为对称结构,注意,由于拆分成了两棵树,我们需要仔细选定函数的参数,根据题意,该操作应分别对应左子节点的左子树和右子节点的右子树,以及左子节点的右子树和右子节点的左子树。
还应注意的是,不要忘记判断节点为空的情况。
解答
/** * 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 true; if(root->left==NULL || root->right==NULL) return false; return isMirrorTree(root->left,root->right); } bool isMirrorTree(TreeNode *p, TreeNode *q){ if(p==NULL && q==NULL) return true; if(p==NULL || q==NULL) return false; if(p->val!=q->val) return false; if((p->left==NULL && p->right==NULL) && (q->left==NULL && q->right==NULL)){ if(p->val==q->val) return true;}return (isMirrorTree(p->left,q->right) && (isMirrorTree(p->right,q->left)));}};时间复杂度为O(n)。
阅读全文
0 0
- Leetcode - Tree - Symmetric Tree
- Leetcode - Tree - Symmetric Tree
- LeetCode[Tree]: Symmetric Tree
- [leetcode][tree] Symmetric Tree
- LeetCode: Symmetric Tree
- [Leetcode] Symmetric Tree
- LeetCode : Symmetric Tree
- leetcode 13:symmetric tree
- [LeetCode] Symmetric Tree - Recursively
- [LeetCode] Symmetric Tree - Iteratively
- [LeetCode] Symmetric Tree
- [LeetCode]Symmetric Tree
- Leetcode:Symmetric Tree
- [Leetcode]Symmetric Tree
- Leetcode: Symmetric Tree
- [leetcode]Symmetric Tree
- LeetCode-Symmetric Tree
- [leetcode] Symmetric Tree
- (框架)新手了解的一部分知识点--慢慢补充
- SpringCloud——Eureka服务注册和发现
- VB.NET七层登录
- excel表格下载
- 二级购物车
- [LeetCode]--Symmetric Tree
- Neural Networks API
- 几个不错的android开源依赖
- Netty【三】 TCP 粘包和拆包
- 百度ueditor富文本编辑器使用 以及去除自动保存
- SQL Server2014导入导出数据及报错
- 映射组成关系
- logstash 中filter中的date插件
- 7天教你玩转云服务器