-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode_101_Symmetric_Tree.java
More file actions
44 lines (41 loc) · 1.53 KB
/
Copy pathLeetCode_101_Symmetric_Tree.java
File metadata and controls
44 lines (41 loc) · 1.53 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
/**
* Definition for a binary tree node.
* 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;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
// If the root is null, the tree is symmetric (an empty tree is symmetric)
return root == null || check_Symmetrical(root.left, root.right);
}
/**
* This helper method checks if two subtrees are symmetric.
*
* @param left The root of the left subtree
* @param right The root of the right subtree
* @return true if the two subtrees are symmetric, false otherwise
*/
public boolean check_Symmetrical(TreeNode left, TreeNode right) {
// If both nodes are null, they are symmetric
if (left == null || right == null) {
return left == right; // true if both are null, false if one is null
}
// If the values of the nodes are not equal, the trees are not symmetric
if (left.val != right.val) {
return false;
}
// Recursively check the left subtree of the left node and the right subtree of the right node
// and the right subtree of the left node and the left subtree of the right node
return check_Symmetrical(left.left, right.right) && check_Symmetrical(left.right, right.left);
}
}