[LeetCode-interview algorithm classic-Java implementation] [101-Symmetric Tree], leetcode -- java
[101-Symmetric Tree )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Original question
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
Note:
Bonus points if you cocould solve it both recursively and iteratively.
Theme
Give a tree and determine whether it is symmetric. That is, whether the left subtree of the tree is an image of the right subtree.
Solutions
Use recursion to solve the problem. First, judge whether the Left and Right subnodes are equal. If the values are not equal, false is returned. If the values are equal, the left subtree of the Left subnode is compared with the right subnode of the right subnode, compare the left subtree of the Left subtree with the left subtree of the right subtree. true is returned only when both are true; otherwise, false is returned.
Code Implementation
Tree node class
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}
Algorithm Implementation class
public class Solution { public boolean isSymmetric(TreeNode root) { if (root == null) { return true; } else { return isSame(root.left, root.right); } } private boolean isSame(TreeNode left, TreeNode right) { if (left == null && right == null) { return true; } if (left != null && right == null || left == null && right != null){ return false; } else { return left.val == right.val && isSame(left.left, right.right) && isSame(left.right, right.left); } }}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note
Please refer to the source for reprinting [http://blog.csdn.net/derrantcm/article/details/47333335]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.