Symmetric Tree

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     }

 

你可能感兴趣的:(tree)