@@ -219,6 +219,114 @@ func max(a, b int) int {
219
219
}
220
220
```
221
221
222
+ ### ** C**
223
+
224
+ ``` c
225
+ /* *
226
+ * Definition for a binary tree node.
227
+ * struct TreeNode {
228
+ * int val;
229
+ * struct TreeNode *left;
230
+ * struct TreeNode *right;
231
+ * };
232
+ */
233
+
234
+ #define max (a,b ) (((a) > (b)) ? (a) : (b))
235
+
236
+ int dfs (struct TreeNode * root, int * res) {
237
+ if (!root) {
238
+ return 0;
239
+ }
240
+ int left = dfs(root->left, res);
241
+ int right = dfs(root->right, res);
242
+ * res = max(* res, left + right);
243
+ return max(left, right) + 1;
244
+ }
245
+
246
+ int diameterOfBinaryTree(struct TreeNode * root) {
247
+ int res = 0;
248
+ dfs(root, &res);
249
+ return res;
250
+ }
251
+ ```
252
+
253
+ ### **TypeScript**
254
+
255
+ ```ts
256
+ /**
257
+ * Definition for a binary tree node.
258
+ * class TreeNode {
259
+ * val: number
260
+ * left: TreeNode | null
261
+ * right: TreeNode | null
262
+ * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
263
+ * this.val = (val===undefined ? 0 : val)
264
+ * this.left = (left===undefined ? null : left)
265
+ * this.right = (right===undefined ? null : right)
266
+ * }
267
+ * }
268
+ */
269
+
270
+ function diameterOfBinaryTree(root: TreeNode | null): number {
271
+ let res = 0;
272
+ const dfs = (root: TreeNode | null) => {
273
+ if (root == null) {
274
+ return 0;
275
+ }
276
+ const { left, right } = root;
277
+ const l = dfs(left);
278
+ const r = dfs(right);
279
+ res = Math.max(res, l + r);
280
+ return Math.max(l, r) + 1;
281
+ };
282
+ dfs(root);
283
+ return res;
284
+ }
285
+ ```
286
+
287
+ ### ** Rust**
288
+
289
+ ``` rust
290
+ // Definition for a binary tree node.
291
+ // #[derive(Debug, PartialEq, Eq)]
292
+ // pub struct TreeNode {
293
+ // pub val: i32,
294
+ // pub left: Option<Rc<RefCell<TreeNode>>>,
295
+ // pub right: Option<Rc<RefCell<TreeNode>>>,
296
+ // }
297
+ //
298
+ // impl TreeNode {
299
+ // #[inline]
300
+ // pub fn new(val: i32) -> Self {
301
+ // TreeNode {
302
+ // val,
303
+ // left: None,
304
+ // right: None
305
+ // }
306
+ // }
307
+ // }
308
+ use std :: rc :: Rc ;
309
+ use std :: cell :: RefCell ;
310
+ impl Solution {
311
+ fn dfs (root : & Option <Rc <RefCell <TreeNode >>>, res : & mut i32 ) -> i32 {
312
+ if root . is_none () {
313
+ return 0 ;
314
+ }
315
+ let root = root . as_ref (). unwrap (). as_ref (). borrow ();
316
+ let left = Self :: dfs (& root . left, res );
317
+ let right = Self :: dfs (& root . right, res );
318
+ * res = (* res ). max (left + right );
319
+ left . max (right ) + 1
320
+ }
321
+
322
+ pub fn diameter_of_binary_tree (root : Option <Rc <RefCell <TreeNode >>>) -> i32 {
323
+ let mut res = 0 ;
324
+ Self :: dfs (& root , & mut res );
325
+ res
326
+ }
327
+ }
328
+ ```
329
+
222
330
### ** ...**
223
331
224
332
```
0 commit comments