Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”


📢 preface

🚀 Algorithm 🚀
  • 🌲 punch in an algorithm every day, which is not only a learning process, but also a sharing process 😜
  • 🌲 tip: the programming languages used in this column are C# and Java
  • 🌲 to maintain a state of learning every day, let us work together to become a god of algorithms 🧐!
  • 🌲 today is the 29th day 🎈!
🚀 Algorithm 🚀

🌲 Convert an ordered array to a binary search tree

Given an array of integers, numS, whose elements are sorted in ascending order, convert it into a highly balanced binary search tree.

A highly balanced binary tree is one that satisfies the requirement that the absolute value of the height difference between the left and right subtrees of each node is no more than 1.

Example 1: Input: nums = [-, 10-3,0,5,9] output: [0, 3, 9, 10, null, 5] : [0, 10, 5, null, 3, null, 9] also will be deemed to be the correct answer: Example 2: Input: nums = [1,3] output: [3,1] explanation: [1,3] and [3,1] are both highly balanced binary search trees.

Tip:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • Nums are arranged in strict ascending order

🌻C# method: middle-order traversal

On the meaning of binary search tree, here is the explanation of the force to give you a reference to see

In order traversal, always choose the number to the left of the middle position as the root node

If the number on the left of the middle position is selected as the root node, the subscript of the root node is mid=(left+right)/2, and the division method is integer division.

Code:

public class Solution {
    static bool func(TreeNode x, TreeNode y) {
        if (x == null) {
            return y == null;
        }

        if (y == null|| x.val ! = y.val) {return false;
        }

        return func(x.left, y.right) && func(x.right, y.left);
    }


    public bool IsSymmetric(TreeNode root) {
        return root == null ? true: func(root.left, root.right); }}Copy the code

The execution result

By execution time:92Ms, in all CDefeated 59.72% of users in # submissionMemory consumption:25.1MB, in all CBeat 22.92% of users in # commit
Copy the code

Complexity analysis

Time complexity: O(n) where n is the length of the array. Each number is accessed only once. Space complexity: O(log n), where n is the length of the array. The spatial complexity does not consider the return value, so the spatial complexity depends primarily on the depth of the recursive stack, which is O(logn).Copy the code

🌻Java Method 1: Sequential traversal

Thinking analytical

Always choose the number to the left of the middle position as the root node

If the number on the left of the middle position is selected as the root node, the subscript of the root node is mid=(left+right)/2, and the division method is integer division.

Code:

class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return helper(nums, 0, nums.length - 1);
    }

    public TreeNode helper(int[] nums, int left, int right) {
        if (left > right) {
            return null;
        }

        // Always select the number to the left of the middle position as the root node
        int mid = (left + right) / 2;

        TreeNode root = new TreeNode(nums[mid]);
        root.left = helper(nums, left, mid - 1);
        root.right = helper(nums, mid + 1, right);
        returnroot; }}Copy the code

The execution result

By execution time:0Ms, beat out all Java commits100.00% user memory consumption:38.2MB, beat out all Java commits36.59% of the userCopy the code

Complexity analysis

Time complexity: O(n) where n is the length of the array. Each number is accessed only once. Space complexity: O(log n), where n is the length of the array. The spatial complexity does not consider the return value, so the spatial complexity depends primarily on the depth of the recursive stack, which is O(logn).Copy the code

🌻Java method 2: Select any number in the middle as the root node

Thinking analytical

If any middle digit is selected as the root node, the subscripts of the root node are mid=(left+right)/2 and mid=(left+right+1)/2

Choose one of the two at random, where the division is integer division.

Code:

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int p1 = 0, p2 = 0;
        int[] sorted = new int[m + n];
        int cur;
        while (p1 < m || p2 < n) {
            if (p1 == m) {
                cur = nums2[p2++];
            } else if (p2 == n) {
                cur = nums1[p1++];
            } else if (nums1[p1] < nums2[p2]) {
                cur = nums1[p1++];
            } else {
                cur = nums2[p2++];
            }
            sorted[p1 + p2 - 1] = cur;
        }
        for (int i = 0; i ! = m + n; ++i) { nums1[i] = sorted[i]; }}}Copy the code

The execution result

By execution time:0Ms, beat out all Java commits100.00% user memory consumption:38.3MB, beat out all Java commits18.28% of the userCopy the code

Complexity analysis

Time complexity: O(n) Space complexity: O(log n)Copy the code

💬 summary

  • Today is the 29th day of buckle algorithm clocking!
  • The article USES theC# andJavaTwo programming languages to solve the problem
  • Some methods are also written by the god of reference force buckle, and they are also shared while learning, thanks again to the algorithm masters
  • That’s the end of today’s algorithm sharing, see you tomorrow!