leetcode: code base

Posted by lar5 on Fri, 19 Nov 2021 07:20:03 +0100

Word writing

  1. Arrays.sort(nums);
  2. StringBuffer  deleteCharAt
  3. For (int, I = 0, j = n - 1, POS = n - 1; I < = J;), start += 2 * k update steps
  4. int ans = Integer.MAX_VALUE;
  5. map.put(tree[i], map.getOrDefault(tree[i], 0) + 1);
  6. map.remove,. map.get(),map.
  7. Map<Character, Integer>
  8.  for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
            }
  9. contains
  10. When converting an Object type to an int type in Java, you cannot convert it directly. First convert the Object type to a String type, and then convert the String type to an int type!
  11. Object value=null;
  12. Integer.parseInt(String.valueOf(value));
  13. char[] array = str.toCharArray();
  14. equals
  15. containsKey
  16. Stack<Character> stack=new Stack<>();stack.push,stack.pop()

  17. Integer.valueOf(tokens[i]) character to value

  18. Deque<Integer> queue1 = new LinkedList<Integer>();offer() peek() poll()

  19. PriorityQueue<int[]> pq = new PriorityQueue<int[]>(new Comparator<int[]>() {
                public int compare(int[] pair1, int[] pair2) {
                    return pair1[0] != pair2[0] ? pair2[0] - pair1[0] : pair2[1] - pair1[1];
                }
            });

  20. Collections.reverse(res);

  21. dictionary.get(a).compareTo(dictionary.get(b) dictionary order

array

1) Thought

Dichotomy, double pointer, sliding window; Do not return sequence number, but sort

2) Special template

When finding the shortest continuous array
int ans = Integer.MAX_VALUE;
int right=0;
int left=0;
while(right<s.length)
{
    //Update window content (add right)
    while(Meet window conditions&&left<=right)
    {
        ans=Math.min(ans,right-left+1);
        //Update window contents (remove left)
        left++;
    }
    right++
}
 return ans == Integer.MAX_VALUE ? 0 : ans;
When finding the longest continuous array
int ans = 0;
int right=0;
int left=0;
while(right<s.length)
{
    //Update window content (add right)
    while(Window condition not met&&left<=right)
    {
        
        //Update window contents (remove left)
        left++;
    }
    ans=Math.max(ans,right-left+1);
    right++
}
 return ans;

3) Title

209. Minimum length subarray     subject

Given a   n   An array of positive integers and a positive integer target.

Find out the continuous subarray with the smallest length satisfying its sum ≥ target in the array   [numsl, numsl + 1,..., numsr-1, numsr], and returns its length. If there is no eligible subarray, 0 is returned.

class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        int n = nums.length;
        if (n == 0) {
            return 0;
        }
        int ans = Integer.MAX_VALUE;
        int start = 0, end = 0;
        int sum = 0;
        while (end < n) {
            sum += nums[end];
            while (sum >= s) {
                ans = Math.min(ans, end - start + 1);
                sum -= nums[start];
                start++;
            }
            end++;
        }
        return ans == Integer.MAX_VALUE ? 0 : ans;
    }
}

Sword finger Offer 40. Minimum number of k

 
class Solution {
    public int[] getLeastNumbers(int[] arr, int k) 
    {
        int[] ret=new int[k];
         getTopKMinBySort(arr,0,arr.length-1,k);
         /* findKthSmallest Will change the array so that the first k numbers are the smallest K numbers */
    for (int i = 0; i < k; i++)
        ret[i]=arr[i];
    return ret;
    }
 
    public static int partion(int a[],int first,int end){
        int i=first;//Initialization i
        int main=a[end];//The division basis is smaller than main on the left
        for(int j=first;j<end;j++){
             if(a[j]<main){//Less than the basis is placed on the left
                int temp=a[j];//a[j] is interchangeable with a[i]
                a[j]=a[i];
                a[i]=temp;//a[i] store numbers greater than main
                i++;//Subscript plus one to store the next number greater than main
             }
        }
        a[end]=a[i];//a[i] and a[end] are interchangeable, that is, I becomes the subscript of the division basis
        a[i]=main;
        return i;    
    }
 
    public static  void getTopKMinBySort(int a[],int first,int end,int k){//When the division subscript ends with 9, so as to find the 10th largest number, and the number on the left is greater than it, so as to find the number of the first 10
      if(first<end){
          int partionIndex=partion(a,first,end);//Get partition subscript
          int m=partionIndex-first+1;
          if(m==k)return;//Just divide the subscript to 9
          else if(m>k)getTopKMinBySort(a,first,partionIndex-1,k);//It shows that the elements on the left of arr[i] are greater than k, so only the k-largest element in arr[first, i-1] can be recursive
          else getTopKMinBySort(a,partionIndex+1,end,k-m);//Note that the k-th largest element is on the right side of arr[i], so only the k-i-th largest element in arr[i+1, n] can be recursive
      }
   }
}

153. Find the minimum value in the rotation sort array

subject
An array of length n is known, which is arranged in ascending order in advance. After 1 to n rotations, the input array is obtained. For example, the original array num = [0,1,2,4,5,6,7] may be obtained after changing:
If you rotate 4 times, you can get [4,5,6,7,0,1,2]
If you rotate 7 times, you can get [0,1,2,4,5,6,7]
Note that the array [a [0], a [1], a [2],..., a [n-1]] is rotated once, and the result is array [a [n-1], a [0], a [1], a [2],..., a [n-2]].

Give you an array nums with different element values. It was originally an array arranged in ascending order and rotated many times according to the above situation. Please find and return the smallest element in the array.

class Solution {
    public int findMin(int[] nums) {
    int l = 0, h = nums.length-1;
    while (l <=h) {
        int mid = l + (h - l) / 2;
        if(nums[mid]==nums[h])
        return nums[mid];
        if(nums[mid]>nums[h])
        l=mid+1;
        else h=mid;
    }
    return nums[l];
    }
}

Linked list

1) Thought

Linked list: double pointer (leading node); Save the breakpoint, that is, save the node after the breakpoint

2) Special template

Reverse linked list

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;
    }
 
    }

How to unify quickly when the length difference is gap.

// Length difference
 curA = headA;
        int gap = lenA - lenB;
        // Make curA and curB at the same starting point (align the end position)
        while (gap--) {
            curA = curA->next;
        }

3) Title

142. Ring linked list II

subject
Given a linked list, return the first node from the linked list into the ring. If the linked list is acyclic, null is returned.

In order to represent the rings in a given list, we use the integer pos to represent the position where the tail of the list is connected to the list (the index starts from 0). If pos is - 1, there is no ring in the linked list. Note that pos is only used to identify the ring and is not passed to the function as an argument.

Note: it is not allowed to modify the given linked list.

Advanced:

Can you use O(1) space to solve this problem?

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode slow=new ListNode();
        slow=head;
        ListNode fast=new ListNode();
        fast=head;
        while(fast!=null)
        {
            if(fast.next!=null)
                fast=fast.next.next;
            else return null;
            slow=slow.next;
            if(slow==fast)
            break;
        }
        if(fast==null) return null;
        fast=head;
        while(slow!=fast)
        {
            slow=slow.next;
            fast=fast.next;
        }
        return slow;
    }
 }

Set:

1) Thought

26 bit characters can be used as arrays. Array hash; Sort,

There is no need to set up lists, and since there is no repetition, set is used to reduce the amount of calculation.

Who is the key and who is the value

2) Title

1002. Find common characters

subject

Given A string array A with only lowercase letters, returns A list of all characters (including repeated characters) displayed in each string in the list. For example, if A character appears 3 times in each string, but not 4 times, you need to include the character 3 times in the final answer.

You can return answers in any order.

class Solution {
    public List<String> commonChars(String[] words) {
        int[][] arr=new int[words.length][26];
        List<String> list=new ArrayList<String>();
        for(int i=0;i<words.length;i++)
        {
            String str=words[i];
            for(int j=0;j<words[i].length();j++)
                arr[i][str.charAt(j)-'a']++;
            //String key = new String(array);
        }
        for(int i=0;i<26;i++)
        {
            int num=arr[0][i];
            int min=num;
            if(num!=0)
            {
                for(int j=1;j<words.length;j++)
                {
                    if(arr[j][i]==0)
                        break;
                    if(min>arr[j][i])
                    {
                        min=arr[j][i];
                    }
                    if(j==words.length-1)
                    {
                        while(min-->0)
                            list.add(String.valueOf((char)(i+'a')));
 
                    }
               
 
 
                }
 
            }
            
            
            
        }
        return list;
 
 
    }
}

202. Happy number

subject
Write an algorithm to judge whether a number n is a happy number.

"Happy number" is defined as:

For a positive integer, replace the number with the square sum of the numbers at each position each time.
Then repeat the process until the number becomes 1, or it may be an infinite loop, but it never becomes 1.
If it can become   1, then this number is the happy number.
If n is a happy number, return true; If not, false is returned.

class Solution {
    int bitSquareSum(int n) {
        int sum = 0;
        while(n > 0)
        {
            int bit = n % 10;
            sum += bit * bit;
            n = n / 10;
        }
        return sum;
    }
    
    public boolean isHappy(int n) {
        int slow = n, fast = n;
        do{
            slow = bitSquareSum(slow);
            fast = bitSquareSum(fast);
            fast = bitSquareSum(fast);
        }while(slow != fast&&fast!=1);
        
        return fast == 1;
    }
 
    }
 
 

15. Sum of three

subject

Give you an array of n integers   Num, judge   nums   Whether there are three elements a, B, C in such a way that   a + b + c = 0 ? Please find all triples with sum 0 and no repetition.

Note: the answer cannot contain duplicate triples.

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> list=new ArrayList<List<Integer>>();
        //Map<Integer,Integer> map=new HashMap<Integer,Integer>();
      
      if(nums.length<3||nums==null)
      return list;
       Arrays.sort(nums);
       for(int i=0;i<nums.length;i++)
       {
           if(i>0&&nums[i]==nums[i-1])
                continue;
            if(nums[i]>0)
            break;
            int left=i+1;
            int right=nums.length-1;
            while(left<right)
            {
                if(nums[i]+nums[left]+nums[right]==0)
                {
                     List<Integer> listarr=new ArrayList<Integer>();
                        listarr.add(nums[i]);
                        listarr.add(nums[left]);
                        listarr.add(nums[right]);
                        list.add(listarr);
                        while(left<right&&nums[left]==nums[left+1])
                    left++;
                    while(left<right&&nums[right]==nums[right-1])
                    right--;
                    left++;
                    right--;
                }else if(nums[i]+nums[left]+nums[right]>0)
                right--;
                else left++;
 
                
 
            }
            
       }
       return list;
       /*  //for(int i=0;i<nums.length;i++)
        //    map.put(nums[i],map.getOrDefault(nums[i],0)+1);
        for(int i=0;i<nums.length;i++)
            for(int j=1+1;j<nums.length&&j!=i;j++)
            {
                if(map.containsKey(-(nums[j]+nums[i]))&&map.get(-(nums[j]+nums[i]))!=i&&map.get(-(nums[j]+nums[i]))!=j)
                {
                    int count=map.get(-(nums[j]+nums[i]));
                    List<Integer> listarr=new ArrayList<Integer>();
                        listarr.add(nums[i]);
                        listarr.add(nums[j]);
                        listarr.add(-(nums[j]+nums[i]));
                        list.add(listarr);
                       // System.out.println(listarr);
                   
                }
                else map.put(nums[j],j);
                    
            }
            */
           // return list;
    }
}

18. Sum of four numbers

subject
Give you an array of n integers, nums, and a target value, target. Please find and return the quads [nums[a], nums[b], nums[c], nums[d]]:

0 <= a, b, c, d < n
a. b, c and d are different from each other
nums[a] + nums[b] + nums[c] + nums[d] == target
You can return answers in any order.

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> list=new ArrayList<List<Integer>>();
        if(nums.length<4||nums==null)
        return list;
        Arrays.sort(nums);
        for(int i=0;i<nums.length-3;i++)
        {
            if(i>0&&nums[i]==nums[i-1])
            continue;
            if(target>0&&nums[i]>target)
            break;
            for(int j=i+1;j<nums.length-2;j++)
            {
                if(j>i+1&&nums[j]==nums[j-1])
                continue;
                int left=j+1;
                int right=nums.length-1;
                if(target>0&&nums[i]+nums[j]>target)
                break;
                while(left<right)
                {
                    if(nums[i]+nums[j]+nums[left]+nums[right]==target)
                    {
                        List<Integer> listarr=new ArrayList<Integer>();
                        listarr.add(nums[i]);
                        listarr.add(nums[j]);
                        listarr.add(nums[left]);
                        listarr.add(nums[right]);
                        list.add(listarr);
                        while(left<right&&nums[left]==nums[left+1])
                        left++;
                        while(left<right&&nums[right]==nums[right-1])
                        right--;
                         left++;
                         right--;
                    }else if(nums[i]+nums[j]+nums[left]+nums[right]>target)
                    right--;
                    else left++;
                   
                } 
            }
 
        }
        return list;
 
    }
}

character string

1) Train of thought

str.setCharAt(left, temp1)

str.insert(i, "%20");

Note str.length(), str.deleteCharAt(i);str.insert(i,   "%20");str.toString();str.charAt(i) sb.reverse();

Use of functions

Convert to char [] or stringBuffer to directly assign the original String, or directly create a new String and add it as required, or String a new String and then+=

2) Template

class Solution {
    public int strStr(String haystack, String needle) {
        int n = haystack.length(), m = needle.length();
        if (m == 0) {
            return 0;
        }
        int[] pi = new int[m];
        for (int i = 1, j = 0; i < m; i++) {
            while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
                j=pi[j - 1];
            }
            if (needle.charAt(i) == needle.charAt(j)) {
                j++;
            }
            pi[i]=j;
        }
        for (int i = 0, j = 0; i < n; i++) {
            while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
                j = pi[j - 1];
            }
            if (haystack.charAt(i) == needle.charAt(j)) {
                j++;
            }
            if (j == m) {
                return i - m + 1;
            }
        }
        return -1;
    }
}

3) Title

459. Duplicate substring

subject

Given a non empty string, judge whether it can be composed of one of its substrings repeated many times. The given string contains only lowercase English letters and is no longer than 10000.

class Solution {
    public boolean repeatedSubstringPattern(String s) {
        String str = s + s;
        return str.substring(1, str.length() - 1).contains(s);
       //return kmp(str.substring(1, str.length() - 1), s);
    }
}

Stack and queue

1) Thought

Pay attention to whether pop is empty

Use of double ended queues in queues

In the future, pay attention to selecting the maximum value, and consider priority queue (heap), monotone queue and stack)

Usage scenario:

1. Matching problem

2. For the most value, use monotone queue, stack, heap (priority queue), or set

2) Template

Bucket sorting

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
    Map<Integer, Integer> frequencyForNum = new HashMap<>();
    for (int num : nums) {
        frequencyForNum.put(num, frequencyForNum.getOrDefault(num, 0) + 1);
    }//Number of key s, value, frequency
    List<Integer>[] buckets=new ArrayList[nums.length+1];
    //List<Integer>[] buckets = new ArrayList[nums.length + 1];
    for(int key:frequencyForNum.keySet())
    {
        if(buckets[frequencyForNum.get(key)]==null)
        buckets[frequencyForNum.get(key)]=new ArrayList<>();
        buckets[frequencyForNum.get(key)].add(key);
    }
    List<Integer> topK = new ArrayList<>();
    for(int i=buckets.length-1;i>=0&&topK.size()<k;i--)
    {
        if(buckets[i]==null)
        continue;
        if(buckets[i].size()<=(k-topK.size()))
        topK.addAll(buckets[i]);
        else topK.addAll(buckets[i].subList(0,k-topK.size()));
    }
    int[] num=new int[k];
    for(int i=0;i<k;i++)
    {
        num[i]=topK.get(i);
    }
    return num;
 
    }
}

tree

1) Thought

For traversal related problems, (you can start right and then left) think about the relationship with the well-known BFS/DFS, and think of the last node of each layer of the required machine test DFS.

The particularity of binary search tree (the middle order traversal is incremental, the size of left and right nodes, and the middle order results are converted into arrays for processing

2) Template

level traversal

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
         List<List<Integer>> res = new ArrayList<>();
         Queue<TreeNode> queue = new ArrayDeque<>();
         if(root!=null)
         queue.add(root);
         while(!queue.isEmpty())
         {
             int n=queue.size();
             List<Integer> array = new ArrayList<>();
             for(int i=0;i<n;i++)
             {
                 TreeNode node=queue.poll();
                 array.add(node.val);
                 if(node.left!=null)
                 queue.add(node.left);
                 if(node.right!=null)
                 queue.add(node.right);
             }
             res.add(array);
         }
         return res;
    }
}

Recursive version level traversal

class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Integer> counts = new ArrayList<Integer>();
        List<Double> sums = new ArrayList<Double>();
        dfs(root, 0, counts, sums);
        List<Double> averages = new ArrayList<Double>();
        int size = sums.size();
        for (int i = 0; i < size; i++) {
            averages.add(sums.get(i) / counts.get(i));
        }
        return averages;
    }
 
    public void dfs(TreeNode root, int level, List<Integer> counts, List<Double> sums) {
        if (root == null) {
            return;
        }
        if (level < sums.size()) {
            sums.set(level, sums.get(level) + root.val);
            counts.set(level, counts.get(level) + 1);
        } else {
            sums.add(1.0 * root.val);
            counts.add(1);
        }
        dfs(root.left, level + 1, counts, sums);
        dfs(root.right, level + 1, counts, sums);
    }
}

3) Title

116. Populate the next right node pointer for each node

subject
Given a perfect binary tree, all leaf nodes are in the same layer, and each parent node has two child nodes. Binary tree is defined as follows:

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}
Fill in each of its next pointers so that this pointer points to its next right node. If the next right node cannot be found, set the next pointer to NULL.

In the initial state, all next pointers are set to NULL.

/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;
    public Node() {}
    
    public Node(int _val) {
        val = _val;
    }
    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/
class Solution {
    public Node connect(Node root) {
         LinkedList<Node> queue = new LinkedList<>();
         if(root!=null)
         queue.add(root);
         while(queue.size()>0)
         {
             int n=queue.size();
             Node node=queue.get(0);
             for(int i=1;i<n;i++)
             {
                 node.next=queue.get(i);
                 node=queue.get(i);
             }
             for(int i=0;i<n;i++)
             {
                 node=queue.remove();
                 if(node.left!=null)
                 queue.add(node.left);
                 if(node.right!=null)
                 queue.add(node.right);                 
             }
         }
         return root;
    }
}

543. Diameter of binary tree

Given a binary tree, you need to calculate its diameter and length. The diameter length of a binary tree is the maximum of the path lengths of any two nodes. This path may or may not pass through the root node.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int max=0;
    public int diameterOfBinaryTree(TreeNode root) {
        depth(root);
        return max-1;
    }
    public int depth(TreeNode node)
    {
        if(node==null)
        return 0;
        int left=depth(node.left);//Left subtree height
        int right=depth(node.right);//Right subtree height
        max=Math.max(max,left+right+1);//Number of nodes passed by node
        return Math.max(left,right)+1;//Height of node
    }
}

It is very clever to turn the path to the number of nodes, and then to the left subtree depth + right subtree depth + 1 of a node

112. Path sum

Give you the root node of the binary tree   Root and an integer representing the target and   Targetsum: judge whether there is a path from the root node to the leaf node in the tree. The sum of all node values on this path is equal to the target sum   targetSum .

A leaf node is a node that has no children.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root==null)
        return false;
        if(root.right==null&&root.left==null&&root.val==targetSum)
        return true;   
        return hasPathSum(root.right,targetSum-root.val)||hasPathSum(root.left,targetSum-root.val);
        }
        
        
    }

687. Longest same value path

subject

Given a binary tree, find the longest path, and each node in this path has the same value. This path may or may not pass through the root node.

Note: the path length between two nodes is determined by the number of edges between them

class Solution {
    public int max=0;
    public int arrowLength(TreeNode root) {
       if(root==null)
        return 0;
        int left=arrowLength(root.left);
        int right=arrowLength(root.right);
        int leftlen=0,rightlen=0;
        if(root.left!=null&&root.left.val==root.val)
        leftlen=left+1;
        if(root.right!=null&&root.right.val==root.val)
        rightlen=right+1;
        max=Math.max(max,leftlen+rightlen);
        return Math.max(leftlen,rightlen);
    }
    public int longestUnivaluePath(TreeNode root) {
       arrowLength(root) ;
       return max;
    }
}

236. Nearest common ancestor of binary tree

subject

Given a binary tree, find the nearest common ancestor of two specified nodes in the tree.

Baidu Encyclopedia defines the nearest public ancestor as: "for two nodes p and q with root tree T, the nearest public ancestor is expressed as a node x, which satisfies that x is the ancestor of p and q, and the depth of X is as large as possible (a node can also be its own ancestor)."

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null||p==root||q==root)
        return root;
        TreeNode left=lowestCommonAncestor(root.left,p,q);
        TreeNode right=lowestCommonAncestor(root.right,p,q);
        if(left==null&&right==null)
        return null;
        if(left==null)
        return right;
        if(right==null)
        return left;
        return root;
 
        
    }
}

230. The K-th smallest element in the binary search tree

subject

Given the root node root of a binary search tree and an integer k, please design an algorithm to find the second node   k   Minimum elements (counting from 1).

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int number;
    public int num=0;
    public int kthSmallest(TreeNode root, int k) {
        if(root==null)
        return -1;
        kthSmallestdfs(root,k);
        return number;
 
    }
    public void kthSmallestdfs(TreeNode node,int k)
    {
        if(node==null)
        return ;
        kthSmallestdfs(node.left,k);
        num++;
        if(num==k)
        {
            number=node.val;
 
        }
        
        //System.out.println(node.val+" "+num);
        kthSmallestdfs(node.right,k);
 
    }
}

108. Convert an ordered array into a binary search tree

subject

Give you an integer array nums, in which the elements have been arranged in ascending order. Please convert it into a highly balanced binary search tree.

A height balanced binary tree is a binary tree that satisfies the requirement that the absolute value of the height difference between the left and right subtrees of each node does not exceed 1.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
 
 
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums==null)
        return null;
        return bulider(nums,0,nums.length-1);
    }
    public TreeNode bulider(int[] nums,int left,int right)
    {
        if(left>right)
        return null;
        int mid=(left+right+1)/2;
        TreeNode node=new TreeNode(nums[mid]);
        node.left=bulider(nums,left,mid-1);
        node.right=bulider(nums,mid+1,right);
        return node;
    }
}

109. Ordered linked list transformation binary search tree

subject

Given a single linked list, the elements are sorted in ascending order and transformed into a highly balanced binary search tree.

In this question, a highly balanced binary tree refers to each node of a binary tree   The absolute value of the height difference between the left and right subtrees of does not exceed 1.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
 class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if (head == null) return null;
        if (head.next == null) return new TreeNode(head.val);
        ListNode node=preMid(head);
        ListNode nodenext=node.next;
        node.next=null;
        TreeNode t=new TreeNode(nodenext.val);
        t.left=sortedListToBST(head);
        t.right=sortedListToBST(nodenext.next);
        return t;
}
 
private ListNode preMid(ListNode head) {
    ListNode slow = head, fast = head;
    ListNode pre = head;
    while (fast != null && fast.next != null) {
        pre = slow;
        slow = slow.next;
        fast = fast.next.next;
    }
    return pre;
}
 }

530. Minimum absolute difference of binary search tree

subject

Give you a binary search tree with non negative nodes. Please calculate the minimum absolute value of the difference between any two nodes in the tree.

private int minDiff = Integer.MAX_VALUE;
private TreeNode preNode = null;
 
public int getMinimumDifference(TreeNode root) {
    inOrder(root);
    return minDiff;
}
 
private void inOrder(TreeNode node) {
    if (node == null) return;
    inOrder(node.left);
    if (preNode != null) minDiff = Math.min(minDiff, node.val - preNode.val);
    preNode = node;
    inOrder(node.right);
}

13. Interval traversal

subject
After robbing a street and a circle of houses last time, the thief found a new area that could be stolen. There is only one entrance to this area, which we call "root". In addition to the "root", each house has only one "father" house connected to it. After some reconnaissance, the smart thief realized that "the arrangement of all houses in this place is similar to a binary tree". If two directly connected houses are robbed on the same night, the house will automatically call the police.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
 class Solution {
     public int rob(TreeNode root) 
     {
        Map<TreeNode,Integer> map=new HashMap<TreeNode,Integer>();
        return arrowLengthmid(root,map);
        
     }
    public int arrowLengthmid(TreeNode root,Map<TreeNode,Integer> map) {
       if(root==null)
        return 0;
        if(map.containsKey(root))
        return map.get(root);
        int length=root.val;
        if(root.left!=null)
        length+=arrowLengthmid(root.left.left,map)+arrowLengthmid(root.left.right,map);
        if(root.right!=null)
        length+=arrowLengthmid(root.right.left,map)+arrowLengthmid(root.right.right,map);
        int relute=Math.max(length,arrowLengthmid(root.left,map)+arrowLengthmid(root.right,map));
        map.put(root,relute);
        return relute;
    }
}

Topics: Algorithm leetcode