LeetCode algorithm, one question a day, impact Alibaba, day7

1. LeetCode 257. All paths of a binary tree

topic

Given a binary tree, return all paths from the root node to the leaf nodes.
Explanation: A leaf node is a node that has no child nodes.

Ideas and Algorithms

The most intuitive way is to use depth-first search. When traversing a binary tree in a depth-first search, we need to consider the current node and its children.
If the current node is not a leaf node, add the node at the end of the current path, and continue to recursively traverse each child node of the node.
If the current node is a leaf node, after adding the node at the end of the current path, we get a path from the root node to the leaf node, which can be added to the answer.
In this way, after traversing the complete binary tree, we get all the paths from the root node to the leaf node.

Xiaobian cooking solution

public List<String> binaryTreePaths(TreeNode root) {
    
    
    List<String> list = new ArrayList<>();
    constructPaths(root, "", list);
    return list;
}
 
private void constructPaths(TreeNode root, String path, List<String> pathList){
    
    
    if (root != null){
    
    
        StringBuilder builder = new StringBuilder(path);
        builder.append(Integer.toString(root.val));
        if (root.left == null && root.right == null){
    
    //当前节点是叶子节点
            pathList.add(builder.toString()); //把路径加入到答案中
        }else {
    
    
            builder.append("->");//当前结点不是叶子结点,继续递归遍历
            constructPaths(root.left, builder.toString(),pathList);
            constructPaths(root.right, builder.toString(),pathList);
        }
    }
}

2. LeetCode 258. Add up everyone

topic

Given a non-negative integer num, iteratively adds the digits at each bit until the result is a single digit.

Xiaobian problem solving ideas

Add each bit, use recursion, the exit is the length of the result equal to 1

Xiaobian cooking solution

public static int addDigits(int num) {
    
    
    recursion(num);
    return re;
}
 
static int re = 0;
private static void recursion(int num){
    
    
    String str = String.valueOf(num);
    int ret = 0;
    for (int i = 0; i < str.length(); i++) {
    
    
        ret += Integer.parseInt(String.valueOf(str.charAt(i)));
    }
    if(String.valueOf(ret).length() > 1){
    
    
        recursion(ret);
    }else{
    
    
        re = ret;
    }
}

Note that there is a better way to convert char to int.
Character.getNumericValue(str.charAt(i));

Ideas and Algorithms

The solution with time complexity of O(1)O(1):
Except for the one digit, the value of each digit is obtained through the process of (9+1) carry. Think of the dial abacus carry and
treat the integer n as n kinds of items, originally packed in 10 pieces, now take out 1 piece from these 10 pieces in 1 piece, and let them pack 9 pieces as 1 piece.
In this way, there are two parts: the
original 10 items are now 9 items of 1, the packaged items, these, we don't need to
care about the scattered items, they can also be divided into:
the items taken out from the original package, their Sum = "Original number of packages = "Number of times of decimals =" In decimal, the sum of the values ​​in the other digits except the ones digit is
packed with 10 1 part, the scattered items that cannot be entered = 》The value on the decimal unit digit
The total number of scattered items above is the accumulated value obtained after processing num for the first time.
If the accumulated value is > 9, then the value of each digit needs to be added again until the result. to single digits. This means that the above process needs to be repeated.
Then according to the above idea, it seems that the final value can be obtained by n % 9,
but there is a key problem. If num is a multiple of 9, then the above logic does not apply. Originally, I wanted to get the sum of the number of n is packed into 10 1 copies + the number of scattered 10 1 copies that cannot be entered. By taking the modulo with 9, to get the 1 that is not divisible, as a way to calculate the number of shares, but if it is divisible by 9, I can't get that 1, and I can't get the number in the one's place.
So you need to do something special, (num - 1) % 9 + 1
The reason for this: There are n items that can be perfectly divided into 9 pieces. I deliberately remove one, then I can go back to the above logic to get the n items I want to be packaged into 10 pieces. Number + the sum of the scattered numbers that do not fit into 10 aliquots. And this subtracted 1 is equivalent to borrowing from the number of scattered pieces when 10 pieces of 1 are packaged. It does not affect the original number of 10 pieces of 1 package. Take it away first and then put it back. Only affects the number of scatters, so it doesn't matter.

Big boss pointing the country


public int addDigits(int num) {
    
    
    return (num - 1) % 9 + 1;
}

3, LetCode 263. Number of ox

topic

Given an integer n, please judge whether n is an ugly number. If so, return true; otherwise, return false.
Ugly numbers are positive integers that contain only the prime factors 2, 3, and/or 5.

Xiaobian cooking solution

public static boolean isUgly(int n) {
    
    
    if (n<=0){
    
    
        return false;
    }
    int[] nums = {
    
    2,3,5};
    for (int x : nums){
    
    
        if (n%x == 0){
    
    
            n /= x;
        }
    }
    return n == 1;
}

4. Nezha Community

Nezha Cup Open Source SPL Quiz Contest


为什么80%的码农做不了架构师?>>>

Java Column Directory | Click Here

Pay attention to the public number: Nezha programming

Nezha programming updates high-quality articles every week. After paying attention, reply to [CSDN] to receive Java mind maps, Java learning materials, and massive interview materials.

 

Add me WeChat: 18525351592

Pull you into the technical exchange group, there are many technical bigwigs in the group, exchange technology together, advance together, enter the big factory together, and you can buy technical books for free~~

Guess you like

Origin blog.csdn.net/guorui_java/article/details/124335094
Recommended