Symmetric Tree
来源:互联网 发布:php接口的用途 编辑:程序博客网 时间:2024/06/03 12:48
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
\ \
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
思路:题目要求判断一个树其本身是不是对称的。
(1)当这个树为NULL的时候,其本身即为对称,返回true
(2)当这个树不为NULL的时候,如果其左右子树均为NULL,显然也是对称的,返回true
(3)当左右子树有一个为NULL,一个不为NULL的时候,这个树是不对称的,返回false
(4)当左右子树的节点值相等的时候,且左子树的右节点和右子树的左节点是对称,且左子树的左节点和右子树的右节点是对称的时候,整个树是对称的
代码如下所示:
/** * 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) return true; return helper(root->left,root->right); } bool helper(TreeNode* leftNode,TreeNode* rightNode) { if(!leftNode&&!rightNode) return true; if(!leftNode||!rightNode) return false; return leftNode->val==rightNode->val&&helper(leftNode->left,rightNode->right)&&helper(leftNode->right,rightNode->left); }};
0 0
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- 联合会致敬印度成长故事;倡导就业增长的投资
- 视频滤镜参数
- ProgressBar 颜色的设置
- ARM中的时钟
- Android ---Dialog小例
- Symmetric Tree
- HDU 1280 前m大的数(简单HASH)
- 分享一个链接
- Android listView每个item设置不同
- 布隆过滤器实现及应用
- JavaScript学习中的一些笔记
- 常用Docker命令
- 用PC搭建SVN服务器:[1]局域网SVN服务器
- 今天开始学习swift