【Symmetric Tree】cpp

时间:2023-03-09 02:55:35
【Symmetric Tree】cpp

题目:

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.

代码:

/**
* 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 *> staL, staR;
staL.push(root->left);
staR.push(root->right);
while ( !staL.empty() && !staR.empty() )
{
TreeNode *tmpL = staL.top();
staL.pop();
TreeNode *tmpR = staR.top();
staR.pop();
if ( !tmpL && !tmpR ) continue;
if ( !tmpL || !tmpR ) return false;
if ( tmpL->val != tmpR->val ) return false;
staL.push(tmpL->right);
staL.push(tmpL->left);
staR.push(tmpR->left);
staR.push(tmpR->right);
}
return staL.empty() && staR.empty();
}
};

tips:

深搜思想。设立两个栈:左栈和右栈。

从根节点开始:左子树用左栈遍历(node->left->right);右子树用右栈遍历(node->right->left)。

这样就可以转化为Same Tree这道题了(http://www.cnblogs.com/xbf9xbf/p/4505032.html