您的位置:首页 > 其它

LeetCode--Symmetric Tree

2017-11-20 15:12 239 查看
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) {
if (!root) return true;
return isSymmetric(root->left,root->right);
}
bool isSymmetric(TreeNode* p,TreeNode* q){
if(!p&&!q) return true;
if(!p||!q) return false;
return (p->val==q->val)&&isSymmetric(p->left,q->right)&&isSymmetric(p->right,q->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 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)
4000
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: