zoukankan      html  css  js  c++  java
  • 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).


    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * public int val;
    5. * public TreeNode left;
    6. * public TreeNode right;
    7. * public TreeNode(int x) { val = x; }
    8. * }
    9. */
    10. public class Solution {
    11. public int[] FindMode(TreeNode root) {
    12. List<int> modes = new List<int>();
    13. int modeCount = 0, lastValue = int.MinValue, lastValueCount = 0;
    14. Stack<TreeNode> stack = new Stack<TreeNode>();
    15. TreeNode current = root;
    16. while (current != null) {
    17. stack.Push(current);
    18. current = current.left;
    19. }
    20. while (stack.Count != 0) {
    21. current = stack.Pop();
    22. if (current.val == lastValue) {
    23. lastValueCount++;
    24. } else {
    25. lastValue = current.val;
    26. lastValueCount = 1;
    27. }
    28. if (lastValueCount > modeCount) {
    29. modes.Clear();
    30. modes.Add(current.val);
    31. modeCount = lastValueCount;
    32. } else if (lastValueCount == modeCount) {
    33. modes.Add(current.val);
    34. }
    35. TreeNode node = current.right;
    36. while (node != null) {
    37. stack.Push(node);
    38. node = node.left;
    39. }
    40. }
    41. return modes.ToArray();
    42. }
    43. }





  • 相关阅读:
    Android之JSON格式数据解析
    SSH面试题锦集
    Mysql
    (二)Java基础巩固
    (一)Java基础巩固
    (五)Oracle函数 序列 约束 索引
    让css初学者抓狂的属性float
    微信小程序(4)--二维码窗口
    微信小程序(3)--页面跳转和提示框
    微信小程序(2)--下拉刷新和上拉加载更多
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/cfc11b676fdabc12c02882b8e251c80d.html
Copyright © 2011-2022 走看看