101. Symmetric Tree--judging whether the structure of trees is symmetrical

Source: Internet
Author: User

Given a binary tree, check whether it is a mirror of the itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1   /   2   2/\/3  4 4  3

But the following are not:

    1   /   2   2   \      3    3

Note:
Bonus points if you could solve it both recursively and iteratively.

1. Recursion

bool issymmetric (TreeNode *p, TreeNode *q) {    ifreturntrue;     if return false ;         return (P->val = = q->val) &&            issymmetric (P->left, q->right) &&             Issymmetric (P->right, q-> left);}

2. Non-recursive

BOOLIssymmetric (TreeNode *p, TreeNode *P) {Queue<TreeNode*>Q1; Queue<TreeNode*>Q2;    Q1.push (P);    Q2.push (q);  while(Q1.size () >0&& q2.size () >0) {TreeNode* P1 =Q1.front ();        Q1.pop (); TreeNode* P2 =Q2.front ();        Q2.pop (); if(P1==null && P2==null)Continue; if(P1==null | | p2==null)return false; if(P1->val! = p2->val)return false; Q1.push (P1-Left ); Q2.push (P2-Right ); Q1.push (P1-Right ); Q2.push (P2-Left ); }    return true;}

101. Symmetric Tree--judging whether the structure of trees is symmetrical

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.