Leetcode---101. Symmetric Tree

Source: Internet
Author: User
Tags tree serialization

Title Link: Symmetric Tree

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  

But the following are not:

    1    / \   2   2    \   \    3    

Note:

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

Confused what "{1,#,2,3}" means? > read more about how binary tree was serialized on OJ.

OJ ' s Binary Tree serialization:

The serialization of a binary tree follows a level order traversal, where ' # ' signifies a path terminator where no node ex Ists below.

Here's an example:

   1   / \  2   3     /    4     \      

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

The requirement of this question is to judge whether a tree is symmetrical.

The idea of recursion, similar to the same Tree, is only here to judge symmetry.

The two subtrees trees L and R symmetric, that is, the nodes of L and R are the same, and the right subtree of Zuozi and R is symmetric and the right subtree of L and the left subtree of R are symmetric.

Time complexity: O (N)

Space complexity: O (1)

1 class Solution2 {3  Public:4     BOOL Issymmetric(TreeNode *Root)5     {6         if(Root == NULL)7             return true;8         return Issymmetric(Root  -  Left, Root  -  Right);9     }Ten Private: One     BOOL Issymmetric(TreeNode *L, TreeNode *R) A     { -         if(L != NULL && R != NULL) -             return L  - Val == R  - Val  the                 && Issymmetric(L  -  Left, R  -  Right)  -                 && Issymmetric(L  -  Right, R  -  Left); -         Else -             return L == NULL && R == NULL; +     } - };

As for the method of iteration, not to be continued ...

Reprint please indicate source: Leetcode---101. Symmetric Tree

Leetcode---101. 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.