leetcode501

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    Dictionary<int, int> dic = new Dictionary<int, int>();

        /// <summary>
        /// 中序遍历
        /// </summary>
        /// <param name="root"></param>
        private void InNode(TreeNode root)
        {
            if (root != null)
            {
                if (root.left != null)
                {
                    InNode(root.left);
                }

                if (!dic.ContainsKey(root.val))
                {
                    dic.Add(root.val, 1);
                }
                else
                {
                    dic[root.val]++;
                }

                if (root.right != null)
                {
                    InNode(root.right);
                }
            }
        }

        public int[] FindMode(TreeNode root)
        {
            if (root == null)
            {
                return new int[0];
            }
            InNode(root);
            var modelist = new List<int>();
            var list = dic.OrderByDescending(x => x.Value).ToList();
            var maxSize = 0;

            foreach (var d in list)
            {
                if (maxSize <= d.Value)
                {
                    maxSize = d.Value;
                    modelist.Add(d.Key);
                }
                else
                {
                    break;
                }
            }
            return modelist.ToArray();
        }
}

https://leetcode.com/problems/find-mode-in-binary-search-tree/#/description

原文地址:https://www.cnblogs.com/asenyang/p/6739017.html