|
| 1 | +packageeasy; |
| 2 | + |
| 3 | +importclasses.TreeNode; |
| 4 | + |
| 5 | +/**101. Symmetric Tree |
| 6 | +
|
| 7 | + Total Accepted: 121737 |
| 8 | + Total Submissions: 346738 |
| 9 | + Difficulty: Easy |
| 10 | +
|
| 11 | +Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). |
| 12 | +
|
| 13 | +For example, this binary tree [1,2,2,3,4,4,3] is symmetric: |
| 14 | +
|
| 15 | + 1 |
| 16 | + / \ |
| 17 | + 2 2 |
| 18 | + / \ / \ |
| 19 | +3 4 4 3 |
| 20 | +
|
| 21 | +But the following [1,2,2,null,3,null,3] is not: |
| 22 | +
|
| 23 | + 1 |
| 24 | + / \ |
| 25 | + 2 2 |
| 26 | + \ \ |
| 27 | + 3 3 |
| 28 | +
|
| 29 | +Note: |
| 30 | +Bonus points if you could solve it both recursively and iteratively. */ |
| 31 | +publicclassSymmetricTree { |
| 32 | +//a very natural idea flows out using recursion. Cheers. |
| 33 | +publicbooleanisSymmetric(TreeNoderoot) { |
| 34 | +if(root ==null)returntrue; |
| 35 | +returnisSymmetric(root.left,root.right); |
| 36 | +} |
| 37 | + |
| 38 | +privatebooleanisSymmetric(TreeNodeleft,TreeNoderight) { |
| 39 | +if(left ==null ||right ==null)returnleft ==right; |
| 40 | +if(left.val !=right.val)returnfalse; |
| 41 | +returnisSymmetric(left.left,right.right) &&isSymmetric(left.right,right.left); |
| 42 | +} |
| 43 | + |
| 44 | +publicstaticvoidmain(String...strings) { |
| 45 | +SymmetricTreetest =newSymmetricTree(); |
| 46 | +TreeNoderoot =newTreeNode(1); |
| 47 | +System.out.println(test.isSymmetric(root)); |
| 48 | +} |
| 49 | +} |