Skip to content

Instantly share code, notes, and snippets.

@anand-kashyap
Last active February 13, 2023 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anand-kashyap/e06a01618bd765bfb28fdf81dc5495dd to your computer and use it in GitHub Desktop.
Save anand-kashyap/e06a01618bd765bfb28fdf81dc5495dd to your computer and use it in GitHub Desktop.
dsa interview questions - max edge of binary tree & deep copy iterative
// return largest sum of an edge from given binary tree
// out - 2,1, 12,10 = 25
const tree = {
value: 2,
leftNode: {
value: 1,
leftNode: {
value: 12,
leftNode: {
value: 3,
leftNode: null,
rightNode: null,
},
rightNode: {
value: 10,
leftNode: null,
rightNode: null,
}
},
rightNode: {
value: 18,
leftNode: {
value: 1,
leftNode: null,
rightNode: null,
},
rightNode: null
}
},
rightNode: {
value: 27,
leftNode: null,
rightNode: null
}
};
const maxEdgeSum = (obj) => {
let maxSum = 0;
const stack = [{ node: obj, sum: maxSum }];
while (stack.length) {
const { node: current, sum } = stack.pop();
if (current === null) {
maxSum = Math.max(maxSum, sum);
continue;
}
const newSum = sum + current.value;
stack.push({ node: current.leftNode, sum: newSum },
{ node: current.rightNode, sum: newSum });
}
console.log('maxEdgeSum -> maxSum', maxSum)
return maxSum;
}
// maxEdgeSum(tree);
function deepCopyIterative(obj) {
const copy = Array.isArray(obj) ? [] : {};
const stack = [{ source: obj, target: copy }];
while (stack.length > 0) {
const { source, target } = stack.pop();
for (let key in source) {
const val = source[key];
if (typeof val === 'object') {
stack.push({ source: val, target: target[key] = {} });
continue;
}
target[key] = val;
}
}
return copy;
}
const ctr = deepCopyIterative(tree);
ctr.leftNode.leftNode = null;
console.log({ tree, ctr });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment