101. Symmetric Tree
problem description
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.
algorithm thought
本质是树的层次遍历,判断每一层是否是对称的。层次遍历需要用到队列来辅助解决。得到每一层所有的值。最后遍历判断是否对称。但是对于这题,还有个技巧。对于左右子树,采取不同的策略。对于左子树,每次访问完之后,先push左及节点再push右节点。右子树,先push右再左。这样,每次从队列中拿两个节点出来,这两个节点就刚好都是对称节点。我们判断它们是否一样就行,然后继续运行。
/**
* 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) {
TreeNode *left,*right;
if(root==NULL)
return true;
queue<TreeNode*> qu;
qu.push(root->left);
qu.push(root->right);
while(!qu.empty()){
left=qu.front();
qu.pop();
right=qu.front();
qu.pop();
if(left==NULL&&right==NULL)
continue;
if(left==NULL||right==NULL)
return false;
if(left->val!=right->val)
return false;
qu.push(left->left);
qu.push(right->right);
qu.push(left->right);
qu.push(right->left);
}
return true;
}
};
algorithm analysis
时间复杂度就是O(n),遍历一遍树。
Last updated