[Leetcode#101] Symmetric Tree

Source: Internet
Author: User

The problem:

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.

My Analysis:

The problem is little tricky, but it provoides a very important skill in sovling symmetric problem.
Key:the binary tree is the most instance to explore Sysmmetric properity.
Let's think in the this.
The tree A has its mirror B. If A is a sysmmetric tree <==> A and B should be the same.
Apparently, any move on B (left search or right search), it's equal to the Oppsite move on A. (B is the mirror image).
Thus we could use a to emmulate any move on B (just opposite the move).

Return Helper (cur_root1.left, cur_root2.right) && Helper (cur_root1.right, cur_root2.left);

Then, we could use the classic method of testing if the trees is matching, to test on tree A and B (imitate on A).

 Public classSolution { Public Booleanissymmetric (TreeNode root) {if(Root = =NULL)            return true; returnHelper (root, root); }        Private BooleanHelper (TreeNode cur_root1, TreeNode cur_root2) {if(Cur_root1 = =NULL&& Cur_root2 = =NULL)            return true; if(Cur_root1 = =NULL|| Cur_root2 = =NULL)            return false; if(Cur_root1.val! =cur_root2.val)return false; returnHelper (Cur_root1.left, cur_root2.right) &&Helper (cur_root1.right, cur_root2.left); }}

[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.