forked from DHEERAJHARODE/Hacktoberfest2024-Open-source-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerictree.java
121 lines (101 loc) · 2.24 KB
/
generictree.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import java.util.ArrayList;
import java.util.Stack;
public class generictree{
public static void main(String[] args)
{
int[] arr={10, 20, 50, -1, 60, -1, -1, 30, 70, -1, 80, 100, -1, 110, -1, -1, 90, -1, -1, 40, 120, 140, -1, 150, -1, -1, -1,-1};
Node root=create(arr);
display(root);
System.out.println(height(root));
System.out.println(find(root,1101));
ArrayList<Node> path=new ArrayList<>();
findpath(root,110,path);
for(Node p: path)
{
System.out.println( p.data);
}
}
public static class Node
{
int data;
ArrayList<Node> child=new ArrayList<>();
Node(int data)
{
this.data=data;
}
Node(){};
}
public static Node create(int[] arr)
{
Stack<Node> stack=new Stack<>();
for(int i=0;i<arr.length-1;i++)
{
if(arr[i]!=-1)
{
Node n=new Node(arr[i]);
stack.push(n);
}
else
{
Node n=stack.pop();
stack.peek().child.add(n);
}
}
return stack.peek();
}
public static void preorder(Node node)
{
System.out.print(node.data + "");
for(Node ch: node.child)
preorder(ch);
}
public static void display(Node node)
{
String str="";
str+=node.data+"->";
for(Node ch: node.child)
str+=ch.data+" ";
System.out.println(str);
for(Node ch: node.child)
display(ch);
}
public static int height(Node node)
{
int h=0;
for(Node ch: node.child)
{
h=Math.max(h,height(ch));
}
return h+1;
}
public static boolean find(Node node, int val)
{
if(node.data== val)
{
return true;
}
boolean res=false;
for(Node ch: node.child)
{res=res||find(ch,val);
}
return res;
}
public static boolean findpath(Node node,int val,ArrayList<Node> path)
{
if(node.data== val)
{
path.add(node);
return true;
}
boolean res=false;
path.add(node);
for(Node ch : node.child)
{
res=res|| findpath(ch,val,path);
if(!res)
path.remove(path.size()-1);
}
return res;
}
public static
}