码迷,mamicode.com
首页 > 其他好文 > 详细

【Symmetric Tree】cpp

时间:2015-05-15 10:22:50      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

【Symmetric Tree】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4505116.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!