-
-
Notifications
You must be signed in to change notification settings - Fork 8.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add solutions to lc problem: No.1026 (#2538)
No.1026.Maximum Difference Between Node and Ancestor
- Loading branch information
Showing
4 changed files
with
124 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
33 changes: 33 additions & 0 deletions
33
solution/1000-1099/1026.Maximum Difference Between Node and Ancestor/Solution.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
/** | ||
* 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 ans; | ||
|
||
public int MaxAncestorDiff(TreeNode root) { | ||
dfs(root, root.val, root.val); | ||
return ans; | ||
} | ||
|
||
private void dfs(TreeNode root, int mi, int mx) { | ||
if (root == null) { | ||
return; | ||
} | ||
int x = Math.Max(Math.Abs(mi - root.val), Math.Abs(mx - root.val)); | ||
ans = Math.Max(ans, x); | ||
mi = Math.Min(mi, root.val); | ||
mx = Math.Max(mx, root.val); | ||
dfs(root.left, mi, mx); | ||
dfs(root.right, mi, mx); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters