forked from Anuj-Kumar-Sharma/Java-DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainClass.java
More file actions
133 lines (95 loc) · 3.13 KB
/
Copy pathMainClass.java
File metadata and controls
133 lines (95 loc) · 3.13 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
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
122
123
124
125
126
127
128
129
130
131
132
133
package binaryTree2;
import java.util.*;
public class MainClass {
// 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;
}
}
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
ArrayDeque<TreeNode> stack = new ArrayDeque<>();
TreeNode cur = root;
while(cur != null || !stack.isEmpty()) {
while(cur != null) {
stack.push(cur);
cur = cur.left;
}
TreeNode pop = stack.pop();
ans.add(pop.val);
cur = pop.right;
}
return ans;
}
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
if(root == null) return ans;
ArrayDeque<TreeNode> s1 = new ArrayDeque<>();
ArrayDeque<TreeNode> s2 = new ArrayDeque<>();
s1.push(root);
while(!s1.isEmpty()) {
TreeNode pop = s1.pop();
s2.push(pop);
if(pop.left != null) {
s1.push(pop.left);
}
if(pop.right != null) {
s1.push(pop.right);
}
}
while(!s2.isEmpty()) {
ans.add(s2.pop().val);
}
return ans;
}
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
if(root == null) return ans;
ArrayDeque<TreeNode> stack = new ArrayDeque<>();
stack.push(root);
while(!stack.isEmpty()) {
TreeNode pop = stack.pop();
ans.add(pop.val);
if(pop.right != null) {
stack.push(pop.right);
}
if(pop.left != null) {
stack.push(pop.left);
}
}
return ans;
}
public int diameterOfBinaryTree(TreeNode root) {
// if(root == null) return 0;
// int ld = diameterOfBinaryTree(root.left);
// int rd = diameterOfBinaryTree(root.right);
// int lh = height(root.left);
// int rh = height(root.right);
// int cur = lh + rh;
// return Math.max(cur, Math.max(ld, rd));
int a[] = new int[1];
// IntCustom obj = new IntCustom();
height(root, a);
return ans;
// return obj.a;
}
int ans = 0;
int height(TreeNode root, int a[]) {
if(root == null) return 0;
int lh = height(root.left, a);
int rh = height(root.right, a);
ans = Math.max(ans, lh+rh);
// obj.a = Math.max(obj.a, lh+rh);
return Math.max(lh, rh) + 1;
}
public static void main(String[] args) {
}
}