您的位置:首页 > 其它

Symmetric Tree

2015-07-28 13:29 369 查看
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.

confused what
"{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.

Analyse: the same as Same Tree

1. Recursion

Runtime: 8ms.

/**
* 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 symmetric(root->left, root->right);
}
bool symmetric(TreeNode* leftNode, TreeNode* rightNode){
if(!leftNode && !rightNode) return true;
if(!leftNode || !rightNode) return false;

return leftNode->val == rightNode->val &&
symmetric(leftNode->left, rightNode->right) &&
symmetric(leftNode->right, rightNode->left);
}
};


2. Iteration

Runtime: 4ms.

/**
* 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* > stk;
stk.push(root->left);
stk.push(root->right);

while(!stk.empty()){
TreeNode* node1 = stk.top();
stk.pop();
TreeNode* node2 = stk.top();
stk.pop();

if(!node1 && !node2) continue;
if(!node1 || !node2) return false;
if(node1->val != node2->val) return false;

stk.push(node1->left);
stk.push(node2->right);
stk.push(node1->right);
stk.push(node2->left);
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: