101. Symmetric Tree

来源:互联网 发布:ubuntu kylin iso下载 编辑:程序博客网 时间:2024/05/20 05:31

</pre>Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).<p></p><p style="margin-top:0px; margin-bottom:10px; color:rgb(51,51,51); font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; font-size:14px; line-height:30px">For example, this binary tree is symmetric:</p><pre style="overflow:auto; font-family:Menlo,Monaco,Consolas,'Courier New',monospace; font-size:13px; padding:9.5px; margin-top:0px; margin-bottom:10px; line-height:1.42857; color:rgb(51,51,51); word-break:break-all; word-wrap:break-word; border:1px solid rgb(204,204,204); background-color:rgb(245,245,245)">    1   / \  2   2 / \ / \3  4 4  3

But the following is not:

    1   / \  2   2   \   \   3    3
solution:(参考 http://www.2cto.com/kf/201507/416787.html的方法)
</pre>/**<br /> * Definition for a binary tree node.<br /> * struct TreeNode {<br /> *     int val;<br /> *     TreeNode *left;<br /> *     TreeNode *right;<br /> *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}<br /> * };<br /> */<br />class Solution {<br />public:<br />    bool isSymmetric(TreeNode* root) {<br />        if(root==NULL) return true;<br />        stack<TreeNode*> s;<br />        s.push(root->left);<br />        s.push(root->right);<br />        TreeNode *m;<br />        TreeNode *n;<br />        while(!s.empty()){<br />            m = s.top();<br />            s.pop();<br />            n = s.top();<br />            s.pop();<br />            if(!m&&!n) continue;<br />            else if(!m||!n) return false;<br />            else if(m->val!=n->val) return false;<br />            s.push(m->left);<br />            s.push(n->right);<br />            s.push(m->right);<br />            s.push(n->left);<br />        }<br />        return true;<br />    }<br />};<br />
0 0
原创粉丝点击