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).



题目标签:Tree

  这道题目给了我们一个二叉搜索树,让我们找到树的众树 (出现最多的那个值),可以是一个众树,也可以有很多个。看完题目第一个想到用HashMap,但是发现题目最后follow up说不能用extra space。所以我们要另外考虑方法。二叉搜索树的特性,左边 <= 根 <= 右边,这道题目包括了等于。举一个例子:

                      10

                       /      \

5       13

                      /   \         \

3     7       13

/  \      \

2    3     9

  看这个例子,我们试着把它上下压缩一下, 就等于, 2 3 3 5 7 9 10 13 13 ,在纸上画的左右分开比较容易看清。发现这是一个有序的排列。如果我们可以遍历这个顺序的话,它是从小到大的,特点就是,一样的数字一定是连在一起的。这样我们就可以设一个count = 1,一个maxCount = 0 和一个pre Node, count是记录每一个数字的连续出现次数,如果大于maxCount 那就说明这个数字是新的mode,比起之前的数字。 maxCount 记录最大出现次数的mode。pre Node是上一个点的数字,当每次current 点和上一个点比较,是否两个数字相同,来判断需要count++,如果不相同,那就更新count = 1。

  如何得到这个有序排列,可以通过inorder traversal 来实现,需要注意的是, Java 是 Pass by Value 的核心,所以pre node , count 什么的,需要放在function 外面。

Java Solution:

Runtime beats 74.31%

完成日期:07/07/2017

关键词:Tree

关键点:inorder 遍历 (从小到大顺序)

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution
11 {
12     TreeNode pre = null;
13     int cnt = 1;
14     int max_cnt = 0;
15
16     public int[] findMode(TreeNode root)
17     {
18         ArrayList<Integer> res = new ArrayList<>();
19
20         inorder(root, res);
21
22         int[] result = new int[res.size()];
23
24         for(int i=0; i<result.length; i++)
25             result[i] = res.get(i);
26
27         return result;
28     }
29
30     public void inorder(TreeNode node, ArrayList<Integer> res)
31     {
32         if(node == null)
33             return;
34
35         inorder(node.left, res);
36         // meaning this node has a previous node, need to compare them to determine cnt
37         if(pre != null)
38         {
39             if(node.val == pre.val) // if this node has same value as pre‘s
40                 cnt++;
41             else // if this node has different value as pre‘s
42                 cnt = 1;
43         }
44
45         // once cnt is greater max_cnt, meaning find a new mode, need to clear res;
46         if(cnt > max_cnt)
47         {
48             max_cnt = cnt;
49             res.clear();
50             res.add(node.val);
51         }
52         else if(cnt == max_cnt) // cnt == max_cnt, meaning find a new mode that equal to pre mode.
53             res.add(node.val);
54
55
56         if(pre == null) // for first most left leaf node, its pre is null, set the first pre node
57         {
58             pre = new TreeNode(node.val);
59         }
60         else // if pre is not null, update this node‘s val each time
61             pre.val = node.val;
62
63
64         inorder(node.right, res);
65     }
66 }

参考资料:

http://www.cnblogs.com/grandyang/p/6436150.html

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

时间: 2024-10-22 02:05:52

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

[LeetCode] 255. Verify Preorder Sequence in Binary Search Tree 验证二叉搜索树的先序序列

Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree. You may assume each number in the sequence is unique. Follow up:Could you do it using only constant space complexity? 给一个数组,验证是否为一个二叉搜索树的

[CareerCup] 4.5 Validate Binary Search Tree 验证二叉搜索树

4.5 Implement a function to check if a binary tree is a binary search tree. LeetCode上的原理,请参见我之前的博客Validate Binary Search Tree 验证二叉搜索树.

[LeetCode] Validate Binary Search Tree 验证二叉搜索树

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys

[LeetCode] Binary Search Tree Iterator 二叉搜索树迭代器

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Note: next() and hasNext() should run in average O(1) time and uses

[LeetCode] Recover Binary Search Tree 复原二叉搜索树

Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note:A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? confused what "{1,#,2,3}"

[LeetCode] 99. Recover Binary Search Tree 复原二叉搜索树

Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Example 1: Input: [1,3,null,null,2]   1   /  3     2 Output: [3,1,null,null,2]   3   /  1     2 Example 2: Input: [3,1,4,null,null,2]

669. Trim a Binary Search Tree 修剪二叉搜索树

Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R](R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary

669. Trim a Binary Search Tree修剪二叉搜索树

[抄题]: Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed

173 Binary Search Tree Iterator 二叉搜索树迭代器

实现一个二叉搜索树迭代器.你将使用二叉搜索树的根节点初始化迭代器.调用 next() 将返回二叉搜索树中的下一个最小的数.注意: next() 和hasNext() 操作的时间复杂度是O(1),并使用 O(h) 内存,其中 h 是树的高度. 详见:https://leetcode.com/problems/binary-search-tree-iterator/description/ /** * Definition for binary tree * struct TreeNode { *

Binary Search Tree (二叉搜索树)

一直在看Data Structure and Algorithm Analysis 的原版,英文水平有限看的比较慢.代码功力就更不用说了,所以代码打的还没有看书快……已经在看优先队列了,AVL树还没有打完也是棒棒哒.这会儿就先从二叉树更新开始吧. 二叉树的结构什么的基本都知道,二叉搜索树就是比就简单的二叉树多了一个特性(property)——每个节点的左子叶内的key比节点的key小,而其右子叶的key比节点的key大.这个特性不是唯一的(比如左右子叶相对于其父节点的key值大小顺序可以颠倒),