This commit is contained in:
youngyangyang04
2021-08-30 10:07:49 +08:00
parent 5726a73078
commit ce72ff2162
7 changed files with 198 additions and 80 deletions

View File

@@ -9,7 +9,7 @@
> 二叉树上应该怎么求,二叉搜索树上又应该怎么求?
## 501.二叉搜索树中的众数
# 501.二叉搜索树中的众数
[力扣题目链接](https://leetcode-cn.com/problems/find-mode-in-binary-search-tree/solution/)
@@ -33,7 +33,7 @@
进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)
## 思路
# 思路
这道题目呢,递归法我从两个维度来讲。
@@ -321,7 +321,7 @@ public:
};
```
## 总结
# 总结
本题在递归法中,我给出了如果是普通二叉树,应该怎么求众数。
@@ -340,12 +340,13 @@ public:
> **需要强调的是 leetcode上的耗时统计是非常不准确的看个大概就行一样的代码耗时可以差百分之50以上**所以leetcode的耗时统计别太当回事知道理论上的效率优劣就行了。
## 其他语言版本
# 其他语言版本
Java
## Java
暴力法
```java
class Solution {
public int[] findMode(FindModeInBinarySearchTree.TreeNode root) {
@@ -379,6 +380,8 @@ class Solution {
}
```
中序遍历-不使用额外空间,利用二叉搜索树特性
```Java
class Solution {
ArrayList<Integer> resList;
@@ -427,15 +430,11 @@ class Solution {
}
```
Python
## Python
递归法
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# 递归法
class Solution:
def findMode(self, root: TreeNode) -> List[int]:
if not root: return
@@ -460,36 +459,11 @@ class Solution:
return
findNumber(root)
return self.res
```
# 迭代法-中序遍历-使用额外空间map的方法
class Solution:
def findMode(self, root: TreeNode) -> List[int]:
stack = []
cur = root
pre = None
dist = {}
while cur or stack:
if cur: # 指针来访问节点,访问到最底层
stack.append(cur)
cur = cur.left
else: # 逐一处理节点
cur = stack.pop()
if cur.val in dist:
dist[cur.val] += 1
else:
dist[cur.val] = 1
pre = cur
cur = cur.right
# 找出字典中最大的key
res = []
for key, value in dist.items():
if (value == max(dist.values())):
res.append(key)
return res
# 迭代法-中序遍历-不使用额外空间,利用二叉搜索树特性:
迭代法-中序遍历-使用额外空间,利用二叉搜索树特性
```python
class Solution:
def findMode(self, root: TreeNode) -> List[int]:
stack = []
@@ -521,18 +495,11 @@ class Solution:
return res
```
Go
## Go
暴力法非BSL
```go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findMode(root *TreeNode) []int {
var history map[int]int
var maxValue int
@@ -571,15 +538,7 @@ func traversal(root *TreeNode,history map[int]int){
计数法,不使用额外空间,利用二叉树性质,中序遍历
```go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findMode(root *TreeNode) []int {
func findMode(root *TreeNode) []int {
res := make([]int, 0)
count := 1
max := 1
@@ -611,8 +570,9 @@ func traversal(root *TreeNode,history map[int]int){
}
```
JavaScript版本:
使用额外空间map的方法
## JavaScript
使用额外空间map的方法
```javascript
var findMode = function(root) {
// 使用递归中序遍历
@@ -649,8 +609,10 @@ var findMode = function(root) {
}
return res;
};
```
```
不使用额外空间,利用二叉树性质,中序遍历(有序)
```javascript
var findMode = function(root) {
// 不使用额外空间,使用中序遍历,设置出现最大次数初始值为1