leetcode 501. Find Mode in Binary Search Tree

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:

  • The left subtree of a node contains only nodes with keys less than or equal to the node‘s key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node‘s key.
  • Both the left and right subtrees must also be binary search trees.

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.

Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).

粗暴解法,直接hash计数然后找出最大计数的值。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def findMode(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        def dfs(node, cnt):
            if not node: return
            dfs(node.left, cnt)
            cnt[node.val] += 1
            dfs(node.right, cnt)
        cnt = collections.defaultdict(int)
        dfs(root, cnt)
        ans,max_cnt = [],0
        for k,v in cnt.items():
            if v > max_cnt:
                max_cnt = v
                ans = [k]
            elif v == max_cnt and k not in ans:
                ans.append(k)
        return ans

最后几行可以直接使用python max :

mc = max(cnt.values())
return [n for n, c in cnt.items() if c == mc]

另外就是经典的tree node遍历解法,在dfs时候使用pre_node记录上次遍历的node,和当前node值进行比较:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def findMode(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        ans,max_cnt = [],0
        pre_node, pre_cnt = None, 1

        def dfs(node):
            nonlocal ans,max_cnt,pre_node,pre_cnt
            if not node: return
            dfs(node.left)
            if not pre_node: # init
                max_cnt = 1
                ans = [node.val]
            else:
                if node.val == pre_node.val:
                    pre_cnt += 1
                else:
                    pre_cnt = 1
                if pre_cnt > max_cnt:
                    max_cnt = pre_cnt
                    ans = [node.val]
                elif pre_cnt == max_cnt:
                    ans.append(node.val)
            pre_node = node
            dfs(node.right)                

        dfs(root)    

        return ans

python2 下的解法,合理运用dummy value其实非常方便哦!

class Solution(object):
    def findMode(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if root is None:
            return []

        self.curVal = root.val - 1 # dummy value is good!
        self.curNum = 0 # dummy value is good!
        self.maxNum = 0
        self.maxVals = []

        def dfs(root):
            if root is not None:

                dfs(root.right)

                if root.val != self.curVal:
                    self.curNum = 0
                self.curNum = self.curNum + 1
                self.curVal = root.val
                if self.curNum == self.maxNum:
                    self.maxVals.append(self.curVal)
                elif self.curNum > self.maxNum:
                    self.maxNum = self.curNum
                    self.maxVals = [self.curVal]                    

                dfs(root.left)

        dfs(root)
        return self.maxVals

使用stack的解法:

class Solution(object):
    def findMode(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        stack, node, prev, cnt, res = [], root, None, 0, (0, [])
        while stack or node:
            if node:
                stack.append(node)
                node = node.left
            else:
                node = stack.pop()
                if node.val != prev:
                    cnt = 0
                cnt += 1
                if cnt > res[0]:
                    res = (cnt, [node.val])
                elif cnt == res[0]:
                    res[1].append(node.val)
                prev = node.val
                node = node.right
        return res[1]

原文地址:https://www.cnblogs.com/bonelee/p/9147724.html

时间: 2024-08-02 03:12:08

leetcode 501. Find Mode in Binary Search Tree的相关文章

LeetCode 501. Find Mode in Binary Search Tree (找到二叉搜索树的众数)

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: The left subtree of a node contains only nodes with keys less than or equal to the nod

[LeetCode]501. Find Mode in Binary Search Tree二叉搜索树寻找众数

这次是二叉搜索树的遍历 感觉只要和二叉搜索树的题目,都要用到一个重要性质: 中序遍历二叉搜索树的结果是一个递增序列: 而且要注意,在递归遍历树的时候,有些参数如果是要随递归不断更新(也就是如果递归返回上层,参数也需要最新的),就要用全局变量,而不是传参,其实这就是全局变量的定义. 不过如果是保存每层递归内的信息,就需要传参数. 本题显然是需要全局参数 /** * Definition for a binary tree node. * public class TreeNode { * int

LeetCode 501. Find Mode in Binary Search Tree(寻找二叉查找树中出现次数最多的值)

题意:寻找二叉查找树中出现次数最多的值 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int ma = 0; int cnt = 1; TreeNode

[leetcode]Convert Sorted List to Binary Search Tree @ Python

原题地址:http://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ 题意:将一条排序好的链表转换为二叉查找树,二叉查找树需要平衡. 解题思路:两个思路:一,可以使用快慢指针来找到中间的那个节点,然后将这个节点作为树根,并分别递归这个节点左右两边的链表产生左右子树,这样的好处是不需要使用额外的空间,坏处是代码不够整洁.二,将排序好的链表的每个节点的值存入一个数组中,这样就和http://www.cnblog

[leetcode]Convert Sorted Array to Binary Search Tree @ Python

原题地址:http://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ 题意:将一个排序好的数组转换为一颗二叉查找树,这颗二叉查找树要求是平衡的. 解题思路:由于要求二叉查找树是平衡的.所以我们可以选在数组的中间那个数当树根root,然后这个数左边的数组为左子树,右边的数组为右子树,分别递归产生左右子树就可以了. 代码: # Definition for a binary tree node # class

LeetCode: Convert Sorted List to Binary Search Tree [109]

[题目] Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. [题意] 将一个有序链表转换成平衡二叉树 [思路] 思路跟Convert Sorted Array to Binary Search Tree完全一样 [代码] /** * Definition for singly-linked list. * struct List

[LeetCode] Convert Sorted List to Binary Search Tree(分治)

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 方法:为了使BST高度平衡,要找链表中的中值作为当前根节点. /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) :

LeetCode: Convert Sorted Array to Binary Search Tree [108]

[题目] Given an array where elements are sorted in ascending order, convert it to a height balanced BST. [题意] 给定一个已排序的数组(不存在重复元素),将它转换成一棵平衡二叉搜索树. [思路] 由于平衡二叉树要求左右子树的高度差绝对值相遇等于1,也就是说左右子树尽可能包含相同数目节点. 则使用二分法来解本题即可. [代码] /** * Definition for binary tree *

[Leetcode] Binary tree -- 501. Find Mode in Binary Search Tree

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: The left subtree of a node contains only nodes with keys less than or equal to the nod