Created
February 14, 2021 21:56
-
-
Save MohammedALREAI/eb4ddb86311984b6f8b5b69a15007d3c to your computer and use it in GitHub Desktop.
NodeDepth Algrothmic
This file contains hidden or 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
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