-
Notifications
You must be signed in to change notification settings - Fork 187
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #589 from 0xff-dev/865
Add solution and test-cases for problem 865
- Loading branch information
Showing
4 changed files
with
113 additions
and
24 deletions.
There are no files selected for viewing
41 changes: 27 additions & 14 deletions
41
leetcode/801-900/0865.Smallest-Subtree-with-all-the-Deepest-Nodes/README.md
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
55 changes: 53 additions & 2 deletions
55
leetcode/801-900/0865.Smallest-Subtree-with-all-the-Deepest-Nodes/Solution.go
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 |
---|---|---|
@@ -1,5 +1,56 @@ | ||
package Solution | ||
|
||
func Solution(x bool) bool { | ||
return x | ||
type TreeNode struct { | ||
Val int | ||
Left, Right *TreeNode | ||
} | ||
|
||
func Solution(root *TreeNode) *TreeNode { | ||
var dfs func(*TreeNode, int) | ||
maxDep := 0 | ||
targetLeafNodes := 0 | ||
nodeDep := make(map[int]int) | ||
dfs = func(now *TreeNode, dep int) { | ||
if now == nil { | ||
return | ||
} | ||
nodeDep[now.Val] = dep | ||
if now.Left == nil && now.Right == nil { | ||
if dep > maxDep { | ||
maxDep = dep | ||
targetLeafNodes = 1 | ||
} else if dep == maxDep { | ||
targetLeafNodes++ | ||
} | ||
return | ||
} | ||
dfs(now.Left, dep+1) | ||
dfs(now.Right, dep+1) | ||
} | ||
dfs(root, 1) | ||
|
||
var ans *TreeNode | ||
var dfs1 func(*TreeNode) int | ||
dfs1 = func(now *TreeNode) int { | ||
if now == nil { | ||
return 0 | ||
} | ||
left := dfs1(now.Left) | ||
right := dfs1(now.Right) | ||
|
||
addOne := 0 | ||
if nodeDep[now.Val] == maxDep { | ||
addOne = 1 | ||
} | ||
r := left + right + addOne | ||
if r == targetLeafNodes { | ||
if ans == nil || nodeDep[ans.Val] < nodeDep[now.Val] { | ||
ans = now | ||
} | ||
} | ||
return r | ||
} | ||
dfs1(root) | ||
|
||
return ans | ||
} |
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
Binary file added
BIN
+41.9 KB
leetcode/801-900/0865.Smallest-Subtree-with-all-the-Deepest-Nodes/sketch1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.