-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem_04.java
89 lines (83 loc) · 2.1 KB
/
Problem_04.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* LeetCode
* Problem_04.java
*/
package com.deepak.leetcode.Trees;
import java.util.Stack;
import com.deepak.leetcode.Library.TreeNode;
/**
* <br> Problem Statement :
*
* Given two binary trees, write a function to check if they are equal or not.
* Two binary trees are considered equal if they are structurally identical and
* the nodes have the same value.
*
* </br>
*
* @author Deepak
*/
public class Problem_04 {
/**
* Method to check if two trees are same using recursive approach
*
* @param p
* @param q
* @return {@link boolean}
*/
public static <T> boolean isSameTree_Recursive(TreeNode<T> p, TreeNode<T> q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
return p.getVal() == q.getVal() && isSameTree_Recursive(p.getLeft(), q.getLeft())
&& isSameTree_Recursive(p.getRight(), q.getRight());
}
/**
* Method to check if two trees are same using iterative approach
*
* @param p
* @param q
* @return {@link boolean}
*/
public static <T> boolean isSameTree_Iterative(TreeNode<T> p, TreeNode<T> q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
Stack<TreeNode<T>> stackP = new Stack<>();
Stack<TreeNode<T>> stackQ = new Stack<>();
stackP.push(p);
stackQ.push(q);
while (!stackP.isEmpty() && !stackQ.isEmpty()) {
TreeNode<T> nodeP = stackP.pop();
TreeNode<T> nodeQ = stackQ.pop();
if (nodeP.getVal() != nodeQ.getVal()) {
return false;
}
if (nodeP.getLeft() != null && nodeQ.getLeft() != null) {
stackP.push(nodeP.getLeft());
stackQ.push(nodeQ.getLeft());
} else if (nodeP.getLeft() == null && nodeQ.getLeft() == null) {
/* do nothing */
} else {
return false;
}
if (nodeP.getRight() != null && nodeQ.getRight() != null) {
stackP.push(nodeP.getRight());
stackQ.push(nodeQ.getRight());
} else if (nodeP.getRight() == null && nodeQ.getRight() == null) {
/* do nothing */
} else {
return false;
}
}
if (!stackP.isEmpty() || !stackQ.isEmpty()) {
return false;
}
return true;
}
}