当前位置:网站首页>【LeetCode】501. Mode in binary search tree (2 wrong questions)

【LeetCode】501. Mode in binary search tree (2 wrong questions)

2022-07-05 02:20:00 Kaimar

0
1

  • Ideas
    Simple ideas , Traverse in middle order and save the number , Find the maximum number of occurrences , Finally, list the number according to the number of occurrences .
    Using the property of order traversal in binary search tree , Middle order traversal is ordered , So don't save it , You only need to record the number of occurrences and the corresponding value .
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */

func findMode(root *TreeNode) []int {
    
    res := []int{
    }

    var count int
    var maxCount int
    var preNode *TreeNode
    var inOrder func(node *TreeNode) 
    inOrder = func(node *TreeNode) {
    
        if node == nil {
    
            return
        }
        //  Left 
        inOrder(node.Left)
        //  in 
        if preNode == nil {
    
            count = 1
        } else if preNode.Val == node.Val {
    
            count++
        } else {
    
            count = 1
        }

        if count > maxCount {
    
            maxCount = count
            res = []int{
    node.Val}
        } else if count == maxCount {
    
            res = append(res, node.Val)
        }
        preNode = node

        //  Right 
        inOrder(node.Right)
    }
    inOrder(root)
    return res
}

2

原网站

版权声明
本文为[Kaimar]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140933282433.html