use of com.pkumar7.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.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.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.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;
}
use of com.pkumar7.TreeNode in project Data-Structures-Algorithms by pankajgangwar.
the class MarchW4 method helper.
public TreeNode helper(TreeNode root) {
if (root == null)
return null;
if (root.left == null && root.right == null)
return root;
TreeNode leftTail = helper(root.left);
TreeNode rightTail = helper(root.right);
if (leftTail != null) {
leftTail.right = root.right;
root.right = root.left;
root.left = null;
}
return rightTail == null ? leftTail : rightTail;
}
Aggregations