use of com.pkumar7.trees.RootingTree.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class OctoberW1 method allPossibleFBTMemo.
public List<TreeNode> allPossibleFBTMemo(int N, List<TreeNode>[] memo) {
List<TreeNode> res = new ArrayList<>();
if (N == 1) {
res.add(new TreeNode(0));
return res;
}
if (memo[N] != null) {
return memo[N];
}
for (int leftNum = 1; leftNum <= N - 1; leftNum += 2) {
List<TreeNode> left = allPossibleFBTMemo(leftNum, memo);
List<TreeNode> right = allPossibleFBTMemo(N - leftNum - 1, memo);
for (TreeNode currLeft : left) {
for (TreeNode currRight : right) {
TreeNode cur = new TreeNode(0);
cur.left = currLeft;
cur.right = currRight;
res.add(cur);
}
}
}
memo[N] = res;
return res;
}
use of com.pkumar7.trees.RootingTree.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class DecemberW2 method postorderTraversal.
/*
https://leetcode.com/problems/binary-tree-postorder-traversal/
*/
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
res.forEach(ele -> System.out.println(ele));
Stack<TreeNode> stack = new Stack<>();
TreeNode lastNodeVisited = null;
while (!stack.isEmpty() || root != null) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
TreeNode top = stack.peek();
if (top.right != null && lastNodeVisited != top.right) {
root = top.right;
} else {
res.add(top.val);
lastNodeVisited = stack.pop();
}
}
}
return res;
}
use of com.pkumar7.trees.RootingTree.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class FebruaryW1 method bstToGstI.
public TreeNode bstToGstI(TreeNode root) {
sortIncreasing(root);
TreeNode result = toGst(root);
return result;
}
use of com.pkumar7.trees.RootingTree.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class FebruaryW2 method insert.
public TreeNode insert(int val, TreeNode node, Integer[] res, int i, int prefixSum) {
if (node == null) {
node = new TreeNode(val, 0);
res[i] = prefixSum;
} else if (node.val > val) {
node.sum++;
node.left = insert(val, node.left, res, i, prefixSum);
} else if (node.val == val) {
node.dup++;
res[i] = prefixSum + node.sum;
} else {
node.right = insert(val, node.right, res, i, prefixSum + node.dup + node.sum);
}
return node;
}
use of com.pkumar7.trees.RootingTree.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class FebruaryW4 method closestValue.
/* https://leetcode.com/problems/closest-binary-search-tree-value/ */
public int closestValue(TreeNode root, double target) {
int a = root.val;
TreeNode kid = root.val < target ? root.right : root.left;
if (kid == null)
return a;
int b = closestValue(kid, target);
return Math.abs(a - target) < Math.abs(b - target) ? a : b;
}
Aggregations