Skip to content

Commit 341ddaa

Browse files
authored
Merge pull request #1184 from Ykhan799/main
Create: 543-Diameter-of-Binary-Tree.cs, 235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.cs
2 parents 070c51b + 2041205 commit 341ddaa

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* public int val;
5+
* public TreeNode left;
6+
* public TreeNode right;
7+
* public TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
11+
public class Solution {
12+
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
13+
// Traverse Right child
14+
if (p.val > root.val && q.val > root.val) {
15+
return LowestCommonAncestor(root.right, p, q);
16+
}
17+
18+
// Traverse Left Child
19+
if (p.val < root.val && q.val < root.val) {
20+
return LowestCommonAncestor(root.left, p, q);
21+
}
22+
23+
return root;
24+
}
25+
}

Diff for: csharp/543-Diameter-of-Binary-Tree.cs

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* public int val;
5+
* public TreeNode left;
6+
* public TreeNode right;
7+
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
8+
* this.val = val;
9+
* this.left = left;
10+
* this.right = right;
11+
* }
12+
* }
13+
*/
14+
public class Solution {
15+
int result = -1;
16+
17+
public int DiameterOfBinaryTree(TreeNode root) {
18+
dfs(root);
19+
return result;
20+
}
21+
22+
private int dfs(TreeNode current) {
23+
if (current == null) {
24+
return -1;
25+
}
26+
int left = 1 + dfs(current.left);
27+
int right = 1 + dfs(current.right);
28+
result = Math.Max(result, (left + right));
29+
return Math.Max(left, right);
30+
}
31+
}

0 commit comments

Comments
 (0)