forked from LeetCode-in-Net/LeetCode-in-Net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.cs
41 lines (36 loc) · 1.24 KB
/
Solution.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
namespace LeetCodeNet.G0501_0600.S0543_diameter_of_binary_tree {
// #Easy #Top_100_Liked_Questions #Depth_First_Search #Tree #Binary_Tree #Level_2_Day_7_Tree
// #Udemy_Tree_Stack_Queue #Big_O_Time_O(n)_Space_O(n)
// #2024_01_07_Time_74_ms_(84.67%)_Space_42.6_MB_(8.90%)
using LeetCodeNet.Com_github_leetcode;
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
private int diameter;
public int DiameterOfBinaryTree(TreeNode root) {
diameter = 0;
DiameterOfBinaryTreeUtil(root);
return diameter;
}
private int DiameterOfBinaryTreeUtil(TreeNode root) {
if (root == null) {
return 0;
}
int leftLength = root.left != null ? 1 + DiameterOfBinaryTreeUtil(root.left) : 0;
int rightLength = root.right != null ? 1 + DiameterOfBinaryTreeUtil(root.right) : 0;
diameter = Math.Max(diameter, leftLength + rightLength);
return Math.Max(leftLength, rightLength);
}
}
}