您的位置:首页 > 其它

Find Mode in Binary Search Tree

2017-08-09 00:00 274 查看
问题:

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

解决:

① 利用一个哈希表来记录数字和其出现次数之间的映射,然后维护一个变量max来记录当前最多的次数值,这样在遍历完树之后,根据这个max值就能把对应的元素找出来。使用中序遍历方式递归遍历该树(注:使用任何一种遍历方式都可以 )。时间和空间复杂度都是O(N)。

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution { // 16ms
private int max = 0;//因为在两个方法中都使用到了这两个变量,所以将其声明在方法外面。
private Map<Integer,Integer> map = new HashMap<>();
public int[] findMode(TreeNode root) {
if (root == null) return new int[0];
List<Integer> list = new ArrayList<>();
inorder(root);
for (Map.Entry<Integer,Integer> entry : map.entrySet()) {
if(entry.getValue() == max) list.add(entry.getKey());
}
int[] res = new int[list.size()];
for (int i = 0;i < list.size() ;i ++ ) {
res[i] = list.get(i);
}
return res;
}
public void inorder(TreeNode node){
if(node == null) return;
if(node.left != null)inorder(node.left);
map.put(node.val,map.getOrDefault(node.val,0) + 1);
max = Math.max(max,map.get(node.val));
if(node.right != null)inorder(node.right);
}
}

② 中序遍历得到一个递增的序列,使用一个计数器count记录相同的值的个数,max记录最大个数,pre记录前一个节点的值用于判断当前节点与前一个是否相等,从而决定要如何操作count;时间复杂度O(n),空间复杂度O(1)

public class Solution { //5 ms
int pre = Integer.MIN_VALUE;//记录前一个节点数值,用于比较当前节点与之前的节点是否相等
int count = 0;
int max = 0;
public int[] findMode(TreeNode root) {
List<Integer> list = new ArrayList<>();
inorder(root, list);//中序遍历
int[] arr = new int[list.size()];
for(int i = 0;i < arr.length;i ++){
arr[i] = list.get(i);
}
return arr;
}
public void inorder(TreeNode root, List<Integer> list){
if(root != null){
inorder(root.left, list);
if(root.val == pre){
count ++;
}else{
count = 1;
pre = root.val;
}
if(count > max){
max = count;
list.clear();
list.add(root.val);
}else if(count == max){
list.add(root.val);
}
inorder(root.right, list);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: