MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/badcode/comments/o3fan0/check_if_binary_tree_is_balanced/h2c4hfd/?context=3
r/badcode • u/MrPancholi • Jun 19 '21
44 comments sorted by
View all comments
26
Image Transcription: Code
* Definition for a binary tree node. * 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) * } * } */ function getHeightBalanceTupl(root: TreeNode | null): [number,boolean] { if(root===null){ return [0,true]; } const [leftHeight,isLeftBalanced] = getHeightBalanceTupl(root.left); const [rightHeight,isRightBalanced] = getHeightBalanceTupl(root.right); const height = 1 + Math.max(leftHeight,rightHeight); const heightBalance = leftHeight - rightHeight; return [height,isLeftBalanced && isRightBalanced && Math.abs(heightBalance)<=1]; } function isBalanced(root: TreeNode | null): boolean { return getHeightBalanceTupl(root)[1]; };
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
14 u/-HumanResources- Jun 19 '21 Good human.
14
Good human.
26
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jun 19 '21
Image Transcription: Code
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!