use of com.pkumar7.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class JulyW1 method createBST.
TreeNode createBST(List<Integer> nums, int start, int end) {
if (start > end) {
return null;
}
int mid = (start + end) / 2;
TreeNode root = new TreeNode(nums.get(mid));
root.left = createBST(nums, start, mid - 1);
root.right = createBST(nums, mid + 1, end);
return root;
}
use of com.pkumar7.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class JulyW1 method sortedListToBST.
/* LC : 109. Convert Sorted List to Binary Search Tree
* https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
* https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
* Time : O(nlogn)
*/
public TreeNode sortedListToBST(ListNode head) {
if (head == null)
return null;
if (head.next == null)
return new TreeNode(head.val);
ListNode mid = null;
ListNode fast = head, slow = head;
ListNode left = head, right = head;
ListNode prevToMid = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
prevToMid = slow;
slow = slow.next;
}
mid = slow;
if (mid != head) {
prevToMid.next = null;
} else {
left = null;
}
right = mid.next;
TreeNode root = new TreeNode(mid.val);
root.left = sortedListToBST(left);
root.right = sortedListToBST(right);
return root;
}
use of com.pkumar7.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class AprilW2 method findClosestLeaf.
/* https://leetcode.com/problems/closest-leaf-in-a-binary-tree/ */
public int findClosestLeaf(TreeNode root, int k) {
HashMap<TreeNode, ArrayList<TreeNode>> map = new HashMap<>();
buildGraph(root, null, map);
TreeNode target = dfs(root, k);
HashSet<TreeNode> visited = new HashSet<>();
visited.add(target);
Queue<TreeNode> q = new LinkedList<>();
q.offer(target);
while (!q.isEmpty()) {
TreeNode curr = q.poll();
if (curr.left == null && curr.right == null) {
return curr.val;
}
for (TreeNode neig : map.get(curr)) {
if (visited.contains(neig))
continue;
q.offer(neig);
visited.add(neig);
}
}
return -1;
}
use of com.pkumar7.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class AprilW2 method dfs.
public TreeNode dfs(TreeNode root, int k) {
if (root == null)
return null;
if (root.val == k)
return root;
TreeNode left = dfs(root.left, k);
TreeNode right = dfs(root.right, k);
if (left != null) {
return left;
} else {
return right;
}
}
use of com.pkumar7.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class FebruaryW2 method countSmallerTree.
public List<Integer> countSmallerTree(int[] nums) {
int n = nums.length;
Integer[] res = new Integer[n];
TreeNode root = null;
for (int i = n - 1; i >= 0; --i) {
root = insert(nums[i], root, res, i, 0);
}
return Arrays.asList(res);
}
Aggregations