LeetCode Day16 Binary Tree Part 6
Tags: leetcode, java, algorithms, datastructures
Published: 2024-06-24 14:27:14

# LeetCode 530. Minimum Absolute Difference in BST

Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

 

Example 1:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5h93i52rvbyv8tndjzmn.png)
Input: root = [4,2,6,1,3]
Output: 1


Example 2:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rwvdrslh49zw0g3u4rtf.png)
Input: root = [1,0,48,null,null,12,49]
Output: 1
 

Constraints:

The number of nodes in the tree is in the range [2, 104].
0 <= Node.val <= 105
[Original Page](https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/)



## *Wrong Code for the first attempt 

```
    public int getMinimumDifference(TreeNode root) {
        int min = Integer.MAX_VALUE;
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            if(cur !=null){
                if(cur.left!=null){
                    min = Math.min(min, Math.abs(cur.val - cur.left.val));
                }
                if(cur.right !=null){
                    min = Math.min(min, Math.abs(cur.val - cur.right.val));
                }
                queue.offer(cur.left);
                queue.offer(cur.right);
            }
        }
    return min;
    }
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tfpitjwlqhrdute5wa07.png)
The Above code cannot solve the situation when two adjacent elements are not a direct parent-child relationship.

```
    public int getMinimumDifference(TreeNode root) {
        int min = Integer.MAX_VALUE;

        return getMin(root,null, min);


    }
    public int getMin(TreeNode cur,TreeNode pre, int min){
        if(cur == null){
            return min;
        }
        min = getMin(cur.left,pre, min);
        if(pre!=null){
            min = Math.min(min, Math.abs(pre.val-cur.val));
        }
        pre = cur;

        min = getMin(cur.right,pre, min);
        return min;
    }
```




```
    TreeNode pre;
    public int getMinimumDifference(TreeNode root) {
        int min = Integer.MAX_VALUE;

        return getMin(root, min);


    }
    public int getMin(TreeNode cur, int min){
        if(cur == null){
            return min;
        }
        min = getMin(cur.left, min);
        if(pre!=null){
            min = Math.min(min, Math.abs(pre.val-cur.val));
        }

        min = getMin(cur.right, min);
        return min;
    }
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/13hoxg0i8jcwy9ht9r3p.png)
it will cause some problem that the 1st element is not the first element the pre will be the first, so it will cause trouble here.
e.g. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0rfh2knqkbtr8ouupa4y.png)

we want 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/plqlzu80ak194pjjckqe.png)

so here it may pre == null will lead to first logic


Here we can also use two value conduct this problem
```
    public int getMinimumDifference(TreeNode root) {
        int[] min = {Integer.MAX_VALUE};
        getMin(root,null, min);
        return min[0];


    }
    public TreeNode getMin(TreeNode cur,TreeNode pre, int[] min){
        if(cur == null){
            return pre;
        }
        pre = getMin(cur.left,pre, min);
        if(pre!=null){
            min[0] = Math.min(min[0], Math.abs(pre.val-cur.val));
        }
        pre = cur;

        pre = getMin(cur.right,pre, min);
        return pre;
    }
```

Be careful Java use Value Pass so it will not work when we pass by using int or others so that we can pass an object it will re-assign element of the array so that will work 

then be careful we pass pre instead of cur, because we want the first pre is start from the left node (if we pass cur it will cause when we start mid-logic, the pre is still not in the right place it will be 1 element earlier than cur, it is not resealable)




# 501. 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:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6xm2dxbq409p7kzgeg4w.png)



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).

[Original Page](https://leetcode.com/problems/find-mode-in-binary-search-tree/description/)



## lol, Practicing Stream is so cool but not efficient, may it work well in real-practice env?
```
    public int[] findMode(TreeNode root) {
        Map<Integer,Integer> map = new HashMap<>();
        map = modeLogic(root,map);

        int max = Collections.max(map.values());

        List<Integer> list = new ArrayList<>();

        list = map.entrySet().stream()
                    .filter(entry -> entry.getValue().equals(max))
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toList());


        return list.stream()
                    .mapToInt(Integer::valueOf)
                    .toArray();
        
    }

    public Map<Integer,Integer> modeLogic(TreeNode cur, Map<Integer,Integer> map){
            if(cur==null){
                return map;
            }
            //left
            modeLogic(cur.left, map);
            //mid
            map.put(cur.val, map.getOrDefault(cur.val, 0)+1);
            //right
            modeLogic(cur.right, map);
            
            return map;
    }
```

## Methode 2. 
Because it is BST, so it will be easier when we use in-order transverse. 
## * Wrong Code 
```
    public int[] findMode(TreeNode root) {
        

        return modeLogic(root, new LinkedList<Integer>(), 0,0,0 );

        
    }

    public List<Integer> modeLogic(TreeNode cur, List<Integer> list, int count, int maxCount, int preVal){
        if(cur == null){
            return list;
        }            
        // left
        modeLogic(cur.left, list, count, maxCount, cur.val);
        // mid logic
        // 1. if we get the same element we increase the count
        if(cur.val == preVal){
            count+=1;
        }else{
            /***  2. if we finish tranverser pre element we need to 
                    i. comparte the count to previous max Count(we want to find mode)
                    ii. if large than before we have to remove the whole saved elements 
                    iii. if equal than before we add the element because it is also a potential mode
            ***/    
            if(count>maxCount){
                maxCount = count;
                list.clear();
                list.add(preVal);
            }else if(count == maxCount){
                list.add(preVal);
            }
            // any way now we have to update the new element and reset the count
            preVal = cur.val;
            count = 1;
        }

        // right
        modeLogic(cur.right, list, count, maxCount, cur.val);

        return list;
    }
```
using this way it will also cause a problem that when we start transverse the left sub-tree is fine-iterated but the mid will not get the previous Val, count and MaxCount so it will cause problem

## Fix Above 

```
    int count;
    int maxCount;
    TreeNode pre;
    List<Integer> list = new LinkedList<>();

    public int[] findMode(TreeNode root) {
        pre = root;
        modeLogic(root);
        return  list.stream()
                    .mapToInt(Integer::intValue)
                    .toArray();
    }

    public void modeLogic(TreeNode cur){
        if(cur == null){

            return;
        }            
        // left
        modeLogic(cur.left);
        // mid logic
        // 1. if we get the same element we increase the count
        if(cur.val == pre.val){
            count+=1;
        }else{
            // any way now we have to update the new element and reset the count
            pre = cur;
            count = 1;
        }

        if(count>maxCount){
            maxCount = count;
            list.clear();
            list.add(pre.val);
        }else if(count == maxCount){
            list.add(pre.val);
        }
        // right
        modeLogic(cur.right);
    }
```