标签:dict more tmp extra sea print following and null
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.
Assume a BST is defined as follows:
For example:
Given BST [1,null,2,2]
,
1 2 / 2
return [2]
.
Note: If a tree has more than one mode, you can return them in any order.
1 if root is None: 2 return [] 3 dic = {} 4 5 def averageOfLevelsHelper(root): 6 7 if root is not None: 8 # print("root: ", root.val) 9 if root.val not in dic: 10 dic[root.val] = 1 11 else: 12 dic[root.val] += 1 13 if root and root.left is not None: 14 averageOfLevelsHelper(root.left) 15 if root and root.right is not None: 16 averageOfLevelsHelper(root.right) 17 averageOfLevelsHelper(root) 18 resLst = [] 19 20 maxV = max([v for v in dic.values()]) 21 for k, v in dic.items(): 22 if v == maxV: 23 resLst.append(k) 24 return resLst
1 if root is None: 2 return [] 3 st = [] 4 p = TreeNode(-1*2**32) 5 p.right = root 6 st.append(p) 7 top = st[0] 8 9 maxCnt = 1 10 currCnt = 1 11 preVal = -1 12 resLst = [] 13 indexAnswer = 0 #indexAnswer in resLst 14 i = 0 #the index of visiting list 15 while (st): 16 top = st.pop() 17 if top.val != preVal: 18 currCnt = 1 19 if top.val != -1*2**32 and currCnt >= maxCnt: 20 resLst.append(top.val) 21 #print ("resLst: ", resLst) 22 23 else: 24 currCnt += 1 25 if currCnt > maxCnt: 26 maxCnt = currCnt 27 indexAnswer = len(resLst) 28 resLst.append(top.val) 29 elif currCnt == maxCnt: 30 resLst.append(top.val) 31 32 preVal = top.val 33 if top.right: 34 tmp = top.right 35 while (tmp): 36 st.append(tmp) 37 tmp = tmp.left 38 39 return resLst[indexAnswer::] 40
[Leetcode] Binary tree -- 501. Find Mode in Binary Search Tree
标签:dict more tmp extra sea print following and null
原文地址:http://www.cnblogs.com/anxin6699/p/7237063.html