-
Notifications
You must be signed in to change notification settings - Fork 0
/
SymmetricTree.java
41 lines (36 loc) · 1005 Bytes
/
SymmetricTree.java
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
package binarytree;
import binarytree.BinaryTreeTest.TreeNode;
/**
* @author Shogo Akiyama
* Solved on 11/04/2019
*
* 101. Symmetric Tree
* https://leetcode.com/problems/symmetric-tree/
* Difficulty: Easy
*
* Approach: Recursion
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Symmetric Tree.
* Memory Usage: 39.1 MB, less than 36.73% of Java online submissions for Symmetric Tree.
*
* @see BinaryTreeTest#testSymmetricTree()
*/
public class SymmetricTree {
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return isSymmetric(root.left, root.right);
}
private boolean isSymmetric(TreeNode leftNode, TreeNode rightNode) {
if (leftNode == null && rightNode == null) {
return true;
}
if (leftNode == null || rightNode == null) {
return false;
}
if (leftNode.val != rightNode.val) {
return false;
}
return isSymmetric(leftNode.left, rightNode.right) && isSymmetric(leftNode.right, rightNode.left);
}
}