@@ -217,6 +217,82 @@ func max(a, b int) int {
217
217
}
218
218
```
219
219
220
+ ### ** TypeScript**
221
+
222
+ ``` ts
223
+ /**
224
+ * Definition for a binary tree node.
225
+ * class TreeNode {
226
+ * val: number
227
+ * left: TreeNode | null
228
+ * right: TreeNode | null
229
+ * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
230
+ * this.val = (val===undefined ? 0 : val)
231
+ * this.left = (left===undefined ? null : left)
232
+ * this.right = (right===undefined ? null : right)
233
+ * }
234
+ * }
235
+ */
236
+
237
+ function isBalanced(root : TreeNode | null ): boolean {
238
+ const dfs = (root : TreeNode | null ) => {
239
+ if (root == null ) {
240
+ return 0 ;
241
+ }
242
+ const left = dfs (root .left );
243
+ const right = dfs (root .right );
244
+ if (left === - 1 || right === - 1 || Math .abs (left - right ) > 1 ) {
245
+ return - 1 ;
246
+ }
247
+ return 1 + Math .max (left , right );
248
+ };
249
+ return dfs (root ) > - 1 ;
250
+ }
251
+ ```
252
+
253
+ ### ** Rust**
254
+
255
+ ``` rust
256
+ // Definition for a binary tree node.
257
+ // #[derive(Debug, PartialEq, Eq)]
258
+ // pub struct TreeNode {
259
+ // pub val: i32,
260
+ // pub left: Option<Rc<RefCell<TreeNode>>>,
261
+ // pub right: Option<Rc<RefCell<TreeNode>>>,
262
+ // }
263
+ //
264
+ // impl TreeNode {
265
+ // #[inline]
266
+ // pub fn new(val: i32) -> Self {
267
+ // TreeNode {
268
+ // val,
269
+ // left: None,
270
+ // right: None
271
+ // }
272
+ // }
273
+ // }
274
+ use std :: rc :: Rc ;
275
+ use std :: cell :: RefCell ;
276
+ impl Solution {
277
+ pub fn is_balanced (root : Option <Rc <RefCell <TreeNode >>>) -> bool {
278
+ Self :: dfs (& root ) > - 1
279
+ }
280
+
281
+ fn dfs (root : & Option <Rc <RefCell <TreeNode >>>) -> i32 {
282
+ if root . is_none () {
283
+ return 0 ;
284
+ }
285
+ let node = root . as_ref (). unwrap (). borrow ();
286
+ let left = Self :: dfs (& node . left);
287
+ let right = Self :: dfs (& node . right);
288
+ if left == - 1 || right == - 1 || (left - right ). abs () > 1 {
289
+ return - 1 ;
290
+ }
291
+ 1 + left . max (right )
292
+ }
293
+ }
294
+ ```
295
+
220
296
### ** ...**
221
297
222
298
```
0 commit comments