国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

501. Find Mode in Binary Search Tree

2019-11-09 19:13:31
字體:
來源:轉載
供稿:網友

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

因為這道題左子節點可能等于根節點和右子節點,宜使用中序遍歷求解。此外,這道題限制空間復雜度O(1),不少sulotion采用hashmap或者list,如果遇到1,2,3,4...n-1,n,n,n的情況,空間復雜度會變成O(n)。所以應該先得到共有幾個modes,再申請空間。代碼如下:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    PRivate int max = 0;    private int currval = 0;    private int currcount = 0;    private int currmodes = 0;    private int[] modes;        public int[] findMode(TreeNode root) {        helper(root);        modes = new int[currmodes];        currcount = 0;        currmodes = 0;        helper(root);        return modes;    }        public void helper(TreeNode root) {        if (root == null) {            return;        }        helper(root.left);        if (root.val != currval) {            currval = root.val;            currcount = 1;        } else {            currcount ++;        }        if (currcount > max) {            max = currcount;            currmodes = 1;        }else if (currcount == max) {            if (modes != null) {                modes[currmodes] = root.val;            }            currmodes ++;        }        helper(root.right);    }}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 晋中市| 宁陵县| 五常市| 彭阳县| 阳山县| 道孚县| 饶河县| 中牟县| 定南县| 伊金霍洛旗| 大英县| 唐河县| 安吉县| 日土县| 肥西县| 商丘市| 龙陵县| 凌源市| 内江市| 绥江县| 海口市| 昌都县| 石景山区| 武陟县| 成都市| 泸西县| 抚远县| 竹山县| 秭归县| 广宗县| 东乌珠穆沁旗| 台江县| 滨州市| 镇平县| 城步| 麻城市| 曲靖市| 大荔县| 洛川县| 灵川县| 枣阳市|