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

Symmetric Tree

时间:2015-06-19 18:09:13      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:

Description:

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

Code:

 1  bool isSymmetric(TreeNode* root) {
 2         if ( root == NULL )
 3             return true;
 4             
 5         stack<TreeNode *>preOrder;
 6         stack<TreeNode *>mirrorPreOrder;
 7         preOrder.push( root );
 8         mirrorPreOrder.push( root );
 9         
10         while( !preOrder.empty() && !mirrorPreOrder.empty() )
11         {
12             TreeNode * p = preOrder.top();
13             TreeNode * q = mirrorPreOrder.top();
14             preOrder.pop();
15             mirrorPreOrder.pop();
16             
17             if ( p->val != q->val 
18             || (p->right ==NULL && q->left) 
19             || (p->right && q->left == NULL)
20             || (p->left == NULL && q->right)
21             || (p->left && q->right==NULL))
22                 return false;
23             else
24             {
25                 if ( p->right && q->left )
26                 {
27                     preOrder.push( p->right );
28                     mirrorPreOrder.push( q->left );
29                 }
30                 if (p->left && q->right )
31                 {
32                     preOrder.push( p->left );
33                     mirrorPreOrder.push( q->right );
34                 }
35             }
36         }
37         //注意检验是否两棵树都访问完毕
38         if ( preOrder.empty() && mirrorPreOrder.empty() )
39             return true;
40         else
41             return false;
42     }

 

Symmetric Tree

标签:

原文地址:http://www.cnblogs.com/happygirl-zjj/p/4589187.html

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