-
Notifications
You must be signed in to change notification settings - Fork 0
/
Symmetric Tree
34 lines (34 loc) · 1.37 KB
/
Symmetric Tree
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
/* Programmer : Dhruv Patel
* Problem Name : Symmetric Tree
* Used In : Leetcode
* Used As : 101
* Problem :
* Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center)
* Definition :
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) {
* val = x;
* }
* }
*
* Thoughts => The solution can be obtained by the recursive calls of left and right subtrees.
* We check the tree's left and right subtrees with a mirror approach.The best analogy would be
* to verifying a object into the mirror.
*/
public class Solution {
static boolean check(TreeNode t1,TreeNode t2){
if(t1 == null && t2 ==null){return true;}
if(t1 == null || t2 == null){return false;}
return (t1.val==t2.val)&&check(t1.left,t2.right)&&check(t1.right,t2.left);
}
public static void main(String args[]) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(2);
System.out.println(check(root,root));
}
}