diff --git a/solution/0100-0199/0110.Balanced Binary Tree/README.md b/solution/0100-0199/0110.Balanced Binary Tree/README.md index fd3bb8ed25e05..bf0a8738ca8b2 100644 --- a/solution/0100-0199/0110.Balanced Binary Tree/README.md +++ b/solution/0100-0199/0110.Balanced Binary Tree/README.md @@ -116,6 +116,34 @@ class Solution { } ``` +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ + var isBalanced = function(root) { + if (root == null) return true; + let left = root.left; + let right = root.right; + return isBalanced(left) && isBalanced(right) && Math.abs(depth(left) - depth(right)) <= 1; +}; + +function depth(root) { + if (root == null) return 0; + return Math.max(depth(root.left), depth(root.right)) + 1; +} +``` + ### **C++** ```cpp diff --git a/solution/0100-0199/0110.Balanced Binary Tree/README_EN.md b/solution/0100-0199/0110.Balanced Binary Tree/README_EN.md index 5ed73ec9998aa..4a0e78d4091aa 100644 --- a/solution/0100-0199/0110.Balanced Binary Tree/README_EN.md +++ b/solution/0100-0199/0110.Balanced Binary Tree/README_EN.md @@ -106,6 +106,34 @@ class Solution { } ``` +### **JavaScript** + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ + var isBalanced = function(root) { + if (root == null) return true; + let left = root.left; + let right = root.right; + return isBalanced(left) && isBalanced(right) && Math.abs(depth(left) - depth(right)) <= 1; +}; + +function depth(root) { + if (root == null) return 0; + return Math.max(depth(root.left), depth(root.right)) + 1; +} +``` + ### **C++** ```cpp diff --git a/solution/0100-0199/0110.Balanced Binary Tree/Solution.js b/solution/0100-0199/0110.Balanced Binary Tree/Solution.js new file mode 100644 index 0000000000000..0c78a0522ffc9 --- /dev/null +++ b/solution/0100-0199/0110.Balanced Binary Tree/Solution.js @@ -0,0 +1,23 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ + var isBalanced = function(root) { + if (root == null) return true; + let left = root.left; + let right = root.right; + return isBalanced(left) && isBalanced(right) && Math.abs(depth(left) - depth(right)) <= 1; +}; + +function depth(root) { + if (root == null) return 0; + return Math.max(depth(root.left), depth(root.right)) + 1; +} \ No newline at end of file