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

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

501. Find Mode in Binary Search Tree

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

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);    }}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 旬邑县| 长葛市| 宁强县| 泾源县| 福安市| 扎鲁特旗| 抚远县| 新兴县| 浦江县| 固阳县| 蓬溪县| 平陆县| 新昌县| 临沧市| 彩票| 嘉荫县| 夏邑县| 武宣县| 福海县| 金阳县| 贺州市| 远安县| 潜山县| 西盟| 铅山县| 疏勒县| 会东县| 凉山| 新泰市| 翁牛特旗| 济阳县| 柳河县| 嘉鱼县| 木兰县| 长泰县| 潮安县| 修武县| 泾源县| 珲春市| 普宁市| 大理市|