-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindModeInBinarySearchTree.java
More file actions
59 lines (39 loc) · 1.38 KB
/
FindModeInBinarySearchTree.java
File metadata and controls
59 lines (39 loc) · 1.38 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
49
50
51
52
53
54
55
56
57
58
59
package leetcode;
import org.omg.CORBA.INTERNAL;
import sun.reflect.generics.tree.Tree;
import java.lang.reflect.Array;
import java.util.*;
public class FindModeInBinarySearchTree {
public static void main(String[] args) {
TreeNode A = new TreeNode(1);
TreeNode B = new TreeNode(2);
TreeNode C = new TreeNode(2);
A.right = B;
B.left = C;
FindModeInBinarySearchTree findModeInBinarySearchTree = new FindModeInBinarySearchTree();
findModeInBinarySearchTree.findMode(A);
}
public int[] findMode(TreeNode root) {
HashSet<Integer> visited = new HashSet<>();
Stack<Integer> duplicate = new Stack();
preorder(root,visited,duplicate);
int[] result = new int[duplicate.size()];
for (int i = 0; i < duplicate.size(); i++) {
result[i] = duplicate.pop();
}
return result;
}
void preorder(TreeNode root, HashSet<Integer> visited, Stack<Integer> duplicate){
if (root == null){
return;
}
System.out.println(root.val);
if (!visited.contains(root.val)){
visited.add(root.val);
}else {
duplicate.push(root.val);
}
preorder(root.left, visited,duplicate );
preorder(root.right, visited,duplicate);
}
}