101. Symmetric Tree
2017-01-04 14:47
190 查看
Q
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:
But the following [1,2,2,null,3,null,3] is not:
Note:
Bonus points if you could solve it both recursively and iteratively.
A
recursively(C)
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ bool judge(struct TreeNode *left, struct TreeNode *right) { if (left == NULL && right == NULL) { return true; } if (left == NULL || right == NULL) { return false; } if (left->val != right->val) { return false; } return (judge(left->left, right->right) && judge(left->right, right->left)); } bool isSymmetric(struct TreeNode* root) { if (root == NULL) { return true; } return judge(root->left, root->right); }
iteratively(C++)
/** * 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; } queue<TreeNode *> q1; queue<TreeNode *> q2; q1.push(root->left); q2.push(root->right); // 每个队列层序遍历 while (!q1.empty() && !q2.empty()) { TreeNode *l1, *l2; l1 = q1.front(); l2 = q2.front(); if (l1->val != l2->val) { return false; } if ((l1->left==NULL&&l2->right!=NULL) || (l1->left!=NULL&&l2->right==NULL)) { return false; } if ((l1->right==NULL&&l2->left!=NULL) || (l1->right!=NULL&&l2->left==NULL)) { return false; } if (l1->left!=NULL && l2->right!=NULL) { q1.push(l1->left); q2.push(l2->right); } if (l1->right!=NULL && l2->left!=NULL) { q1.push(l1->right); q2.push(l2->left); } q1.pop(); q2.pop(); } return true; } };
相关文章推荐
- 101. Symmetric Tree
- 101. Symmetric Tree
- Java for LeetCode 101 Symmetric Tree
- [leetcode-101]Symmetric Tree(c++)
- 【LEETCODE】101-Symmetric Tree
- LeetCode 101:Symmetric Tree
- LeetCode 101. Symmetric Tree(对称的树)
- Easy 21 Symmetric Tree(101)
- LeetCode 101. Symmetric Tree
- 101. Symmetric Tree
- 101. Symmetric Tree
- [leedcode 101] Symmetric Tree
- 【101-Symmetric Tree(对称树)】
- [leetcode 101]Symmetric Tree
- Leetcode #101 Symmetric Tree
- leetcode 101: Symmetric Tree
- 101. Symmetric Tree
- LeetCode题解-101-Symmetric Tree
- Leetcode-101. Symmetric Tree
- leetcode 101: Symmetric Tree