Symmetric Tree
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
判断一棵树是否镜像对称。
刚开始直接中序遍历,看是否是回文。但[1,2,3,3,#,2,#] 这组数据没过。。。
递归,除了根节点以及其两个孩子节点外,其他节点有规律可循。即两个对称节点a与b ,a->left 与b->righ"t相等" , a->right与b->left" 相等"。
/**
* 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 solve(TreeNode* a,TreeNode* b) {
if (!a&&b || a&&!b) return false; // 其中只有一个为空 直接返回false
if (!a&&!b) return true; // 两个都为空 直接返回true
// 都不为空 且节点val不等 直接返回false
if (a->val != b->val) return false;
// 都不为空 且节点val相等 则需要进一步向下判断
return solve(a->left,b->right)&&solve(a->right,b->left);
}
bool isSymmetric(TreeNode* root) {
if (!root) return true;
solve(root->left,root->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;
bool ans = true;
queue<TreeNode*>q;
q.push(root->left);
q.push(root->right);
while (!q.empty()) {
TreeNode* a = q.front();
q.pop();
TreeNode* b = q.front();
q.pop();
if (!a&&b || a&&!b ) { // 只有一个为空
ans = false;
break;
}
if (!a&&!b) { //都为空
continue;
}
if (a&&b) {// 都不为空
if (a->val != b->val) {ans = false;break;}
else {// 依次将相比较的两个节点 加入queue中
q.push(a->left);
q.push(b->right);
q.push(b->left);
q.push(a->right);
}
}
}
return ans;
}
};
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its 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
Note: