use of com.pkumar7.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class NovemberW3 method generateTreesRec.
public List<TreeNode> generateTreesRec(int start, int end) {
List<TreeNode> list = new ArrayList<>();
if (start > end) {
list.add(null);
}
List<TreeNode> lList, rList;
for (int idx = start; idx <= end; idx++) {
lList = generateTreesRec(start, idx - 1);
rList = generateTreesRec(idx + 1, end);
for (TreeNode lTreeNode : lList) {
for (TreeNode rTreeNode : rList) {
TreeNode root = new TreeNode(idx);
root.left = lTreeNode;
root.right = rTreeNode;
list.add(root);
}
}
}
return list;
}
use of com.pkumar7.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class NovemberW3 method morrisTraversal.
/* https://leetcode.com/problems/binary-tree-inorder-traversal/*/
public void morrisTraversal(TreeNode root) {
TreeNode curr = null;
while (root != null) {
if (root.left != null) {
// Connect threadings for root
curr = root.left;
while (curr.right != null && curr.right != root) {
curr = curr.right;
}
if (curr.right != null) {
// Threading already established
curr.right = null;
System.out.println(root.val);
root = root.right;
} else {
// Construct the threading
curr.right = root;
root = root.left;
}
} else {
System.out.println(root.val);
root = root.right;
}
}
}
use of com.pkumar7.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class NovemberW3 method constructRec.
public TreeNode constructRec(int[] nums, int left, int right) {
if (left >= right) {
return null;
}
int max = Integer.MIN_VALUE;
int max_idx = -1;
for (int idx = left; idx < right; idx++) {
if (nums[idx] > max) {
max = nums[idx];
max_idx = idx;
}
}
TreeNode root = new TreeNode(max);
root.left = constructRec(nums, left, max_idx - 1);
root.right = constructRec(nums, max_idx + 1, right);
return root;
}
use of com.pkumar7.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class NovemberW3 method constructUsingStack.
public TreeNode constructUsingStack(int[] nums) {
Deque<TreeNode> stack = new LinkedList<>();
for (int i = 0; i < nums.length; i++) {
TreeNode curr = new TreeNode(nums[i]);
while (!stack.isEmpty() && stack.peek().val < nums[i]) {
curr.left = stack.pop();
}
if (!stack.isEmpty()) {
stack.peek().right = curr;
}
stack.push(curr);
}
return stack.isEmpty() ? null : stack.removeLast();
}
use of com.pkumar7.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class NovemberW3 method formBstFromRec.
public TreeNode formBstFromRec(int[] preOrder, int bound) {
if (idx == preOrder.length || preOrder[idx] > bound) {
return null;
}
TreeNode curr = new TreeNode(preOrder[idx++]);
curr.left = formBstFromRec(preOrder, curr.val);
curr.right = formBstFromRec(preOrder, bound);
return curr;
}
Aggregations