Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c9767e3

Browse files
author
侯利朋
committed
.\173.binary-search-tree-iterator ok
1 parent 084e3a9 commit c9767e3

File tree

2 files changed

+63
-13
lines changed

2 files changed

+63
-13
lines changed

173.binary-search-tree-iterator-1.go

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
* @lc app=leetcode id=173 lang=golang
3+
*
4+
* [173] Binary Search Tree Iterator
5+
*/
6+
/**
7+
* Definition for a binary tree node.
8+
* type TreeNode struct {
9+
* Val int
10+
* Left *TreeNode
11+
* Right *TreeNode
12+
* }
13+
*/
14+
// 44 ms, faster than 77.78%
15+
// 缓存所有节点
16+
type BSTIterator struct {
17+
Buf []int
18+
Index int
19+
}
20+
21+
func Constructor(root *TreeNode) BSTIterator {
22+
// 中序遍历,缓存数据
23+
rtn := BSTIterator{}
24+
inOrder(root, &rtn.Buf)
25+
rtn.Index = 0
26+
return rtn
27+
}
28+
29+
func inOrder(root *TreeNode, seq *[]int) {
30+
if root == nil {
31+
return
32+
}
33+
inOrder(root.Left, seq)
34+
*seq = append(*seq, root.Val)
35+
inOrder(root.Right, seq)
36+
}
37+
38+
/** @return the next smallest number */
39+
func (this *BSTIterator) Next() int {
40+
this.Index++
41+
return this.Buf[this.Index-1]
42+
}
43+
44+
/** @return whether we have a next smallest number */
45+
func (this *BSTIterator) HasNext() bool {
46+
return this.Index < len(this.Buf)
47+
}
48+
49+
/**
50+
* Your BSTIterator object will be instantiated and called as such:
51+
* obj := Constructor(root);
52+
* param_1 := obj.Next();
53+
* param_2 := obj.HasNext();
54+
*/

508.most-frequent-subtree-sum.go

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,14 @@
1414
// 12 ms, faster than 68.85%
1515
// map缓存所有结果
1616
func findFrequentTreeSum(root *TreeNode) []int {
17-
tmp := make(map[int]int)
18-
sum(root, tmp)
17+
if root == nil {
18+
return []int{}
19+
}
20+
counter := make(map[int]int)
21+
sum(root, counter)
1922
maxTime := -1
2023
rtn := []int{}
21-
for k, v := range tmp {
24+
for k, v := range counter {
2225
if v > maxTime {
2326
maxTime = v
2427
rtn = append(rtn, k)
@@ -34,14 +37,7 @@ func sum(root *TreeNode, tmp map[int]int) int {
3437
if root == nil {
3538
return 0
3639
}
37-
l, r := 0, 0
38-
if root.Left != nil {
39-
l = sum(root.Left, tmp)
40-
}
41-
if root.Right != nil {
42-
r = sum(root.Right, tmp)
43-
}
44-
45-
tmp[l+r+root.Val]++ // 只在此处统计一次结果,在上面的left或right判断中不记录,否则会导致多计算一次
46-
return l + r + root.Val
40+
data := sum(root.Left, tmp) + sum(root.Right, tmp) + root.Val
41+
tmp[data]++
42+
return data
4743
}

0 commit comments

Comments
 (0)