Last active
February 13, 2023 08:11
-
-
Save anand-kashyap/e06a01618bd765bfb28fdf81dc5495dd to your computer and use it in GitHub Desktop.
dsa interview questions - max edge of binary tree & deep copy iterative
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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