Symmetric tree <leetcode>

Source: Internet
Author: User

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

For example, this binary tree is unsupported Ric:

 

    1   /   2   2 / \ / 3  4 4  3

 

But the following is not:

1/2 2 \ 3 3


Idea: first, we will use recursion to traverse the Left and Right sub-trees. When different sub-trees are traversed, We will traverse the root node first, then the left child, and finally the right child; when traversing the right subtree, the county traverses the root node, then the right child, and finally the left child, and compares each traversal to a node. The Code is as follows: // No optimization

 1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     bool isSymmetric(TreeNode *root) {13         if(root==NULL)  return true;14         TreeNode *rootl;15         TreeNode *rootr;16         rootl=root->left;17         rootr=root->right;18         return isSame(rootl,rootr);19     }20     21     bool isSame(TreeNode *rootl,TreeNode *rootr)22     {23         if(rootl==NULL||rootr==NULL)24         {25             if(rootl!=NULL||rootr!=NULL)26             {27                 return false;28             }29             else return true;30         }31         32         if(rootl->val!=rootr->val)  return false;33         else34         {35             if(isSame(rootl->left,rootr->right))36             {37                 if(isSame(rootl->right,rootr->left))38                 {39                     return true;40                 }41                 else return false;42             }43             else return false;44         }45         46     }47 };

 

Symmetric tree <leetcode>

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.