Problem
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).
Solutionclass Solution { int count = 0; int maxCount = 0; Integer pre = null; public int[] findMode(TreeNode root) { ListresList = new ArrayList<>(); helper(root, resList); return resList.stream().mapToInt(i->i).toArray(); } private void helper(TreeNode root, List res) { if (root == null) return; helper(root.left, res); if (pre == null) { pre = root.val; count = 1; maxCount = 1; res.add(root.val); } else { if (root.val == pre) { count++; if (count > maxCount) { res.clear(); maxCount = count; } } else { pre = root.val; count = 1; } if (count == maxCount) { res.add(root.val); } } helper(root.right, res); } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/72459.html
摘要:在線網(wǎng)站地址我的微信公眾號完整題目列表從年月日起,每天更新一題,順序從易到難,目前已更新個(gè)題。這是項(xiàng)目地址歡迎一起交流學(xué)習(xí)。 這篇文章記錄我練習(xí)的 LeetCode 題目,語言 JavaScript。 在線網(wǎng)站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公眾號: showImg(htt...
摘要:遞歸法復(fù)雜度時(shí)間空間思路根據(jù)二叉樹的性質(zhì),我們知道當(dāng)遍歷到某個(gè)根節(jié)點(diǎn)時(shí),最近的那個(gè)節(jié)點(diǎn)要么是在子樹里面,要么就是根節(jié)點(diǎn)本身。因?yàn)槲覀冎离x目標(biāo)數(shù)最接近的數(shù)肯定在二叉搜索的路徑上。 Closest Binary Search Tree Value I Given a non-empty binary search tree and a target value, find the va...
摘要:復(fù)雜度思路用一個(gè)變量來記錄當(dāng)前的值,并且在每次之前,比較得到目前的最大值。注意變量的比較不要用代碼 LeetCode[270] Closest Binary Search Tree Value Given a non-empty binary search tree and a target value, find the value in the BST that is close...
Problem Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. Note: Given target value is a floating point.You are guaranteed to have only o...
摘要:如果子樹中有目標(biāo)節(jié)點(diǎn),標(biāo)記為那個(gè)目標(biāo)節(jié)點(diǎn),如果沒有,標(biāo)記為。顯然,如果左子樹右子樹都有標(biāo)記,說明就已經(jīng)找到最小公共祖先了。如果在根節(jié)點(diǎn)為的左右子樹中找的公共祖先,則必定是本身。只有一個(gè)節(jié)點(diǎn)正好左子樹有,右子樹也有的時(shí)候,才是最小公共祖先。 Lowest Common Ancestor of a Binary Search Tree 最新更新請見:https://yanjia.me/zh...
閱讀 3318·2019-08-29 16:17
閱讀 1975·2019-08-29 15:31
閱讀 2645·2019-08-29 14:09
閱讀 2548·2019-08-26 13:52
閱讀 744·2019-08-26 12:21
閱讀 2125·2019-08-26 12:08
閱讀 991·2019-08-23 17:08
閱讀 1922·2019-08-23 16:59