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.
思路:
这道题关键在于理解对称:左边等于右边,这还只理解到了一层,再深入一层:左边的左边等于右边的右边,左边的右边等于右边的左边,这两层理解了就知道怎么迭代和递归了。
1 递归
bool helper(TreeNode *left, TreeNode *right){
if (!left && !right) return true;
if (!left || !right) return false;
return left->val == right->val
&& helper(left->left, right->right)
&& helper(left->right, right->left);
}
bool isSymmetric(TreeNode* root) {
return helper(root, root);
}
2 迭代
迭代的进行需要使用到队列:先入先出。
bool isSymmetric2(TreeNode* root){
queue<TreeNode* > records;
records.push(root);
records.push(root);
while (records.size()){
TreeNode *left = records.front(); records.pop();
TreeNode *right = records.front(); records.pop();
if (!left && !right) continue;
else if (!left || !right) return false;
else if (left->val != right->val) return false;
records.push(left->left);
records.push(right->right);
records.push(left->right);
records.push(right->left);
}
return true;
}