Symmetric Tree 题解
原创文章,拒绝转载
题目来源:https://leetcode.com/problems/symmetric-tree/description/
Description
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
Example
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.
Solution
class Solution {
private:
bool validateSym(TreeNode* left, TreeNode* right) {
if (left == NULL && right == NULL) {
return true;
} else if (left != NULL && right != NULL) {
return (left -> val == right -> val &&
validateSym(left -> left, right -> right) &&
validateSym(left -> right, right -> left));
}
return false;
}
public:
bool isSymmetric(TreeNode* root) {
if (root == NULL) return true;
return validateSym(root -> left, root -> right);
}
};
解题描述
这道题题意是判断给出的二叉树是不是一棵对称二叉树。上面给出的是递归的做法,还是不难想到的,不过迭代的做法就需要一些思路上的转换。不同于以往使用栈来模拟递归,这道题我使用的是队列来模拟节点递归检查的顺序:
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (root == NULL) return true;
queue<TreeNode*> lq, rq;
lq.push(root -> left);
rq.push(root -> right);
while (!lq.empty() && !rq.empty()) {
TreeNode *lnode = lq.front();
lq.pop();
TreeNode* rnode = rq.front();
rq.pop();
if (lnode == NULL && rnode == NULL) {
continue;
} else if (lnode != NULL && rnode != NULL) {
if (lnode -> val != rnode -> val)
return false;
lq.push(lnode -> left);
lq.push(lnode -> right);
rq.push(rnode -> right);
rq.push(rnode -> left);
} else {
return false;
}
}
if (!lq.empty() || !rq.empty())
return false;
else
return true;
}
};