LeetCode 501. Find Mode in Binary Search Tree

原题链接在这里:https://leetcode.com/problems/find-mode-in-binary-search-tree/

题目:

Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.

If the tree has more than one mode, return them in any order.

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.

Example 1:

Input: root = [1,null,2,2]
Output: [2]

Example 2:

Input: root = [0]
Output: [0]

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -105 <= Node.val <= 105

Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).

题解:

Inorder traversal. During traversal, maintain the previous visted node.

If current node has same value, count frequency is incremented by 1.

If count > max, clear res. add root.val.

If count == max, add root.val.

Time Complexity: O(n).

Space: O(1),regardless res and stack space.

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode() {}
 8  *     TreeNode(int val) { this.val = val; }
 9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 class Solution {
17     TreeNode pre;
18     int count = 0;
19     int max = -1;
20     
21     public int[] findMode(TreeNode root) {
22         List<Integer> res = new ArrayList<>();
23         pre = root;
24         inorder(root, res);
25         int [] resArr = new int[res.size()];
26         for(int i = 0; i < resArr.length; i++){
27             resArr[i] = res.get(i);
28         }
29         
30         return resArr;
31     }
32     
33     private void inorder(TreeNode root, List<Integer> res){
34         if(root == null){
35             return;
36         }
37         
38         inorder(root.left, res);
39         count = pre.val == root.val ? count + 1 : 1;
40         if(count > max){
41             max = count;
42             res.clear();
43             res.add(root.val);
44         }else if(count == max){
45             res.add(root.val);
46         }
47         
48         pre = root;
49         inorder(root.right, res);
50     }
51 }

类似Validate Binary Search TreeMinimum Absolute Difference in BST.

posted @ 2017-06-28 08:00  Dylan_Java_NYC  阅读(788)  评论(0编辑  收藏  举报