-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSymmetricTree.java
More file actions
48 lines (40 loc) · 1.26 KB
/
SymmetricTree.java
File metadata and controls
48 lines (40 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* LeetCode problem 101. Symmetric Tree: https://leetcode.com/problems/symmetric-tree/
*/
public class Solution {
/**
* Determines whether the given tree is symmetric
* Time Complexity: O(N), where N = the number of nodes in the given tree
* Every node is visited during traversal.
* <p>
* Space Complexity: O(H), where H = the height of the tree
* Since this solution uses recursion, the call stack at most will have a size equivalent to the height of the tree.
*
* @param root the root of the tree
* @return whether its symmetric
*/
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
return isMirror(root, root);
}
public boolean isMirror(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) return true;
if (t1 == null || t2 == null) return false;
return t1.val == t2.val && isMirror(t1.left, t2.right) && isMirror(t1.right, t2.left);
}
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}