|
@@ -0,0 +1,46 @@
|
|
|
+var cnt int = 1
|
|
|
+var max int = 0
|
|
|
+var pre int = 0
|
|
|
+var ini bool = false
|
|
|
+
|
|
|
+/**
|
|
|
+ * Definition for a binary tree node.
|
|
|
+ * type TreeNode struct {
|
|
|
+ * Val int
|
|
|
+ * Left *TreeNode
|
|
|
+ * Right *TreeNode
|
|
|
+ * }
|
|
|
+ */
|
|
|
+func findMode(root *TreeNode) (res []int) {
|
|
|
+ cnt, max, pre = 1, 0, 0 // Remember to init global variables at the beginning!
|
|
|
+ ini = false
|
|
|
+ if root == nil {
|
|
|
+ return
|
|
|
+ }
|
|
|
+ inorder(root, &res)
|
|
|
+ return
|
|
|
+}
|
|
|
+
|
|
|
+func inorder(root *TreeNode, res *[]int) {
|
|
|
+ if root == nil {
|
|
|
+ return
|
|
|
+ } // Inorder traversal changes BST into increasing sequence.
|
|
|
+ inorder(root.Left, res)
|
|
|
+ if ini {
|
|
|
+ if root.Val == pre {
|
|
|
+ cnt++
|
|
|
+ } else {
|
|
|
+ cnt = 1
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ ini = true
|
|
|
+ }
|
|
|
+ if max < cnt {
|
|
|
+ *res = []int{root.Val}
|
|
|
+ max = cnt
|
|
|
+ } else if max == cnt {
|
|
|
+ *res = append(*res, root.Val)
|
|
|
+ }
|
|
|
+ pre = root.Val
|
|
|
+ inorder(root.Right, res)
|
|
|
+}
|