-
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 #590 from 0xff-dev/1123
Add solution and test-cases for problem 1123
- 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/1101-1200/1123.Lowest-Common-Ancestor-of-Deepest-Leaves/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/1101-1200/1123.Lowest-Common-Ancestor-of-Deepest-Leaves/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/1101-1200/1123.Lowest-Common-Ancestor-of-Deepest-Leaves/sketch1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.