101.Symmetric Tree¶
Tags: Easy
Depth-first Search
Bread-first Search
Links: https://leetcode.com/problems/symmetric-tree/
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.
/**
* 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) {
return root ? isSymmetric(root -> left, root -> right) : true;
}
bool isSymmetric(TreeNode *left, TreeNode *right) {
if (!left && !right) return true;
if (!left || !right) return false;
return left -> val == right -> val
&& isSymmetric(left -> left, right -> right)
&& isSymmetric(right -> left, left -> right);
}
};
非递归写法:
/**
* 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;
stack<TreeNode *> s;
s.push(root -> left);
s.push(root -> right);
while (!s.empty()) {
TreeNode *p = s.top();
s.pop();
TreeNode *q = s.top();
s.pop();
if (!p && !q) continue;
if (!p || !q) return false;
if (p -> val != q -> val) return false;
s.push(p -> left);
s.push(q -> right);
s.push(p -> right);
s.push(q -> left);
}
return true;
}
};
这道题主要是注意考虑的是对称,所以递归写法检验的是left -> left, right -> right
和left -> right, right -> left
。