Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
yennanliu committed Nov 26, 2024
1 parent 678e462 commit b8808cc
Showing 1 changed file with 65 additions and 32 deletions.
97 changes: 65 additions & 32 deletions leetcode_java/src/main/java/dev/workspace5.java
Original file line number Diff line number Diff line change
Expand Up @@ -3472,52 +3472,85 @@ private String getMultiplyStr(String cur, Integer multiply) {
// LC 776
// https://leetcode.ca/2018-01-14-776-Split-BST/
// https://leetcode.ca/all/776.html
// 10.09 am - 10.20 am
// 8.37 PM - 8.50 PM
/**
* Idea : split tree
*
* -> split tree into smaller, bigger array
* -> then build BST again from 2 arrays above
*/

// IDEA : DFS
TreeNode leftTree = new TreeNode();
TreeNode rightTree = new TreeNode();
public TreeNode[] splitBST(TreeNode root, int target) {
TreeNode[] res = new TreeNode[2];

// split to 2 arrays
List<Integer> smaller = new ArrayList<>();
List<Integer> bigger = new ArrayList<>();
buildTreeDfs(root, target);

Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
res[0] = leftTree;
res[1] = rightTree; // ??
return res;
}

// bfs
while(!queue.isEmpty()){
// update array
TreeNode cur = queue.poll();
if (cur.val <= target){
smaller.add(cur.val);
}else{
bigger.add(cur.val);
}
// add to queue
if (cur.left != null){
queue.add(cur.left);
}
if (cur.right != null){
queue.add(cur.right);
}
private TreeNode[] buildTreeDfs(TreeNode root, int target){
if (root == null){
return null;
}
// if (root.val <= target){
// // ??
// this.buildTreeDfs(leftTree, target);
// }else{
// // ?? or return
// this.buildTreeDfs(rightTree, target);
// }
if (root.left != null && root.left.val <= target){

// build tree
TreeNode smallerTree = buildTree(smaller);
TreeNode biggerTree = buildTree(bigger);

// collect result
TreeNode[] res = new TreeNode[2];
res[0] = smallerTree;
res[1] = biggerTree;

return res;
leftTree.left = root.left;
buildTreeDfs(leftTree, target);
}
return null;
}

// public TreeNode[] splitBST(TreeNode root, int target) {
//
// // split to 2 arrays
// List<Integer> smaller = new ArrayList<>();
// List<Integer> bigger = new ArrayList<>();
//
// Queue<TreeNode> queue = new LinkedList<>();
// queue.add(root);
//
// // bfs
// while(!queue.isEmpty()){
// // update array
// TreeNode cur = queue.poll();
// if (cur.val <= target){
// smaller.add(cur.val);
// }else{
// bigger.add(cur.val);
// }
// // add to queue
// if (cur.left != null){
// queue.add(cur.left);
// }
// if (cur.right != null){
// queue.add(cur.right);
// }
// }
//
// // build tree
// TreeNode smallerTree = buildTree(smaller);
// TreeNode biggerTree = buildTree(bigger);
//
// // collect result
// TreeNode[] res = new TreeNode[2];
// res[0] = smallerTree;
// res[1] = biggerTree;
//
// return res;
// }

private TreeNode buildTree(List<Integer> input){
return null;
}
Expand Down

0 comments on commit b8808cc

Please sign in to comment.