您的位置:首页 > 其它

leetcode: Symmetric Tree

2014-07-02 20:21 274 查看
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:

Bonus points if you could solve it both recursively and iteratively.
递归
/**
* Definition for binary tree
* 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 == NULL)
return true;
return core( root->left, root->right);
}
bool core( TreeNode *root_left, TreeNode *root_right){
if( !root_left && !root_right)
return true;
if( !root_left || !root_right)
return false;
return root_left->val == root_right->val && core( root_left->left, root_right->right) && core( root_left->right, root_right->left);
}
};


非递归:

/**
* Definition for binary tree
* 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 == NULL)
return true;
stack< TreeNode *> stk;
stk.push(root->left);
stk.push(root->right);
while( !stk.empty()){
auto p = stk.top();
stk.pop();
auto q = stk.top();
stk.pop();
if( !q && !p)
continue;
if( !q || !p)
return false;
if( p->val == q->val){
stk.push(p->left);
stk.push(q->right);
stk.push(p->right);
stk.push(q->left);
}
else
return false;
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: