Skip to content

Commit 81e067a

Browse files
author
applewjg
committed
SymmetricTree
Change-Id: Ib4dece75b87b545c5f1a1fde03ce54717a3c912a
1 parent f0aed18 commit 81e067a

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

SymmetricTree.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Dec 25, 2014
4+
Problem: Symmetric Tree
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/symmetric-tree/
7+
Notes:
8+
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
9+
For example, this binary tree is symmetric:
10+
1
11+
/ \
12+
2 2
13+
/ \ / \
14+
3 4 4 3
15+
But the following is not:
16+
1
17+
/ \
18+
2 2
19+
\ \
20+
3 3
21+
Note:
22+
Bonus points if you could solve it both recursively and iteratively.
23+
24+
Solution: 1. Recursive solution
25+
*/
26+
27+
/**
28+
* Definition for binary tree
29+
* public class TreeNode {
30+
* int val;
31+
* TreeNode left;
32+
* TreeNode right;
33+
* TreeNode(int x) { val = x; }
34+
* }
35+
*/
36+
public class Solution {
37+
public boolean isSymmetric(TreeNode root) {
38+
if (root == null) return true;
39+
return solve (root.left, root.right);
40+
}
41+
public boolean solve(TreeNode t1, TreeNode t2) {
42+
if (t1 == null && t2 == null) return true;
43+
if (t1 == null && t2 != null || t1 != null && t2 == null || t1.val != t2.val) return false;
44+
return solve(t1.left, t2.right) && solve(t1.right, t2.left);
45+
}
46+
}

0 commit comments

Comments
 (0)