Skip to content

Instantly share code, notes, and snippets.

@MohammedALREAI
Created February 14, 2021 21:56
Show Gist options
  • Save MohammedALREAI/eb4ddb86311984b6f8b5b69a15007d3c to your computer and use it in GitHub Desktop.
Save MohammedALREAI/eb4ddb86311984b6f8b5b69a15007d3c to your computer and use it in GitHub Desktop.
NodeDepth Algrothmic
class TreeNode {
val: number
left: TreeNode | null
right: TreeNode | null
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = (val===undefined ? 0 : val)
this.left = (left===undefined ? null : left)
this.right = (right===undefined ? null : right)
}
}
interface stackShape{
node:TreeNode,
depth:number
}
// time= O(n) s(h) wich h is the length of the tree
function NodeDepth(root:TreeNode):number{
let sumDepth=0
let stack:[stackShape]=[{node:root,depth:0}]
while(stack.length > 0){
const {node,depth}=stack.pop()!
if(!node)continue ;
sumDepth+=depth
if(node.left){
stack.push({node:node.left,depth:depth+1})
}
if(node.right){
stack.push({node:node.right,depth:depth+1})
}
}
return sumDepth
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment