LeetCode_Symmetric Tree
2015-05-02 21:24
351 查看
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its
center).
For example, this binary tree is symmetric:
But the following is not:
根开始,如果根节点的左右不对称,则false,否则,看根节点的左右子树是否对称。
代码:(AC)
错误代码:没有理解对称树的概念。(WA)
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
根开始,如果根节点的左右不对称,则false,否则,看根节点的左右子树是否对称。
代码:(AC)
/** * 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 left_right_Symmetric(TreeNode* pleft,TreeNode* pright) { if(pleft==NULL&&pright==NULL) return true; if(pleft==NULL&&pright!=NULL)return false; if(pleft!=NULL&&pright==NULL)return false; if(pleft->val!=pright->val) return false; return left_right_Symmetric(pleft->left,pright->right)&&left_right_Symmetric(pleft->right,pright->left); } public: bool isSymmetric(TreeNode* root) { if(root == NULL) return true; if(root->left!=NULL&&root->right==NULL) return false; if(root->left==NULL&&root->right!=NULL) return false; if(root->left!=NULL&&root->right!=NULL&&root->left->val!=root->right->val)return false; else return left_right_Symmetric(root->left,root->right); } };
错误代码:没有理解对称树的概念。(WA)
/** * 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 false; else if(root->left!=NULL&&root->right==NULL)return false; else if(root->left==NULL&&root->right==NULL) return true; else if(root->left!=NULL&&root->right!=NULL&&root->left->val!=root->right->val) return false; else if(root->left!=NULL&&root->right!=NULL&&root->left->val==root->right->val) return isSymmetric(root->left)&&isSymmetric(root->right); } };
相关文章推荐
- leetcode: Symmetric Tree
- 【Leetcode】【Easy】Symmetric Tree
- leetcode-Symmetric Tree
- LeetCode(25)-symmetric tree
- leetcode[101]Symmetric Tree
- Leetcode 101. Symmetric Tree 验证树的对称性 解题报告
- LeetCode: Symmetric Tree
- 【LeetCode-面试算法经典-Java实现】【101-Symmetric Tree(对称树)】
- LeetCode101 Symmetric Tree
- LeetCode(101)Symmetric Tree
- [LeetCode-109] Symmetric Tree
- [Leetcode 101, Easy] Symmetric Tree
- [leetcode] Symmetric Tree
- leetcode 101 Symmetric Tree
- leetcode 之 Symmetric Tree
- leetcode-Symmetric Tree 对称树
- LEETCODE--Symmetric Tree
- LeetCode101 Symmetric Tree
- LeetCode-101-Symmetric Tree(判断是否为对称树)
- [LeetCode] Symmetric Tree 判断二叉树是否为对称二叉树