use of com.pkumar7.trees.RootingTree.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class A method dfs.
public TreeNode dfs(int[] pre, int preStart, int preEnd, int[] post, int postStart, int postEnd) {
if (preStart > preEnd)
return null;
TreeNode root = new TreeNode(pre[preStart]);
if (preStart == preEnd)
return root;
int len = postMap.get(pre[preStart + 1]) - postStart + 1;
root.left = dfs(pre, preStart + 1, preStart + len, post, postStart, postMap.get(pre[preStart + 1]));
root.right = dfs(pre, preStart + len + 1, preEnd, post, postMap.get(pre[preStart + 1]) + 1, postEnd - 1);
return root;
}
use of com.pkumar7.trees.RootingTree.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class A method helper.
public TreeNode helper(int[] pre, int[] post) {
TreeNode root = new TreeNode(pre[preIndex++]);
if (root.val != post[postIndex]) {
root.left = helper(pre, post);
}
if (root.val != post[postIndex]) {
root.right = helper(pre, post);
}
postIndex++;
return root;
}
use of com.pkumar7.trees.RootingTree.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class B method bfs.
public TreeNode bfs(TreeNode root, int val, int depth) {
if (depth == 1) {
TreeNode newRoot = new TreeNode(val);
newRoot.left = root;
return newRoot;
}
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
int currD = 0;
outer: while (!q.isEmpty()) {
int size = q.size();
currD += 1;
while (size-- > 0) {
TreeNode curr = q.poll();
if (currD + 1 == depth) {
TreeNode left = new TreeNode(val);
if (curr.left != null) {
TreeNode prevLeft = curr.left;
curr.left = left;
left.left = prevLeft;
} else {
curr.left = left;
}
TreeNode right = new TreeNode(val);
if (curr.right != null) {
TreeNode prevRight = curr.right;
curr.right = right;
right.right = prevRight;
} else {
curr.right = right;
}
} else {
if (curr.left != null) {
q.offer(curr.left);
}
if (curr.right != null) {
q.offer(curr.right);
}
}
}
}
return root;
}
use of com.pkumar7.trees.RootingTree.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class B method constructBst.
public TreeNode constructBst(List<Integer> list, int low, int high) {
if (low > high)
return null;
int mid = low + (high - low) / 2;
TreeNode root = new TreeNode(list.get(mid));
root.left = constructBst(list, low, mid - 1);
root.right = constructBst(list, mid + 1, high);
return root;
}
use of com.pkumar7.trees.RootingTree.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class B method findLCA.
public TreeNode findLCA(TreeNode root, TreeNode p, TreeNode q) {
if (root == null)
return root;
if (root == p || root == q) {
dfs(root);
return root;
}
sets.add(root.val);
TreeNode left = findLCA(root.left, p, q);
TreeNode right = findLCA(root.right, p, q);
if (left != null && right != null) {
return root;
}
if (left != null && right == null) {
return left;
}
if (right != null && left == null) {
return right;
}
return null;
}
Aggregations