Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree was defined as a binary tree in which the depth of the Every node never differ by more than 1.
https://leetcode.com/problems/balanced-binary-tree/
Judging the number given is not a balanced binary tree, the definition of balance refers to any node of the left and right subtree height difference of not more than 1.
A recursive method that returns the height of the tree and returns 1 if the left and right subtree heights differ by more than 1.
1 /**2 * Definition for a binary tree node.3 * Function TreeNode (val) {4 * This.val = val;5 * This.left = This.right = null;6 * }7 */8 /**9 * @param {TreeNode} rootTen * @return {Boolean} One */ A varisbalanced =function(root) { - returnTreeheight (Root) = = = 1?false:true; - the /** - * @return {int} tree ' s height - * return-1 If depth differ of the subtrees is more than 1 - */ + functiontreeheight (node) { - if(node = = =NULL)return0; + if(Node.left = = =NULL&& Node.right = = =NULL)return1; A varLefth =treeheight (node.left); at varRighth =treeheight (node.right); - if(Lefth = = = 1 | | righth = =-1)return-1; - if(Math.Abs (lefth-righth) > 1)return-1; - returnMath.max (lefth, righth) + 1; - } -};
[Leetcode] [JavaScript] Balanced Binary Tree