Leetcode:symmetric Tree

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.

Analysis:

1. Recursive method. If a tree is symmetric, its left and right sub-trees are mirrored symmetrically. For judging whether the two trees are mirrored symmetrical, if the root node values of the two trees are the same, and the left child of tree A is mirrored symmetrical with the right child of tree B and the right side of tree A is mirrored symmetrically to the left of tree B, then the tree A and B are mirrored symmetrically. The code is as follows:

1 classSolution {2  Public:3     BOOLIssymmetric (TreeNode *root) {4         if(Root = NULL)return true;5         returnIs_mirror (Root->left, root->Right );6     }7     BOOLIs_mirror (TreeNode *l, TreeNode *R) {8         if(L = = NULL | | r = = NULL)returnL = =R;9         if(L->val! = r->val)return false;Ten         returnIs_mirror (L->left, R->right) && is_mirror (L->right, r->Left ); One     } A};

Iterative algorithm is a variant of the iterative traversal algorithm using the stack tree. The main idea is to push the symmetric two nodes to the stack at the same time, and then each time from the top of the stack pop two to determine whether the same. The code is as follows:

classSolution { Public:    BOOLIssymmetric (TreeNode *root) {        if(Root = NULL)return true; Stack<treenode *>s; S.push (Root-Left ); S.push (Root-Right );  while(!S.empty ()) {TreeNode*r =s.top (); S.pop (); TreeNode*l =s.top (); S.pop (); if(r = = NULL && L = = null)Continue;//This is very import            if(r = = NULL | | l = = NULL)return false; if(R->val! = l->val)return false; S.push (R-Left ); S.push (L-Right ); S.push (R-Right ); S.push (L-Left ); }                return true; }};

Leetcode:symmetric Tree

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.