[LC] 108 issues an ordered array into a binary search tree (contribution)

① title

An ordered array in accordance with the ascending order, is converted to a highly balanced binary search tree.

In this problem, a highly balanced binary tree is a binary tree refers to the left and right sub-tree of each node is the height difference between the absolute value of not more than 1.

Example:

Given an ordered array: [-10, -3,0,5,9],

One possible answer is: [0, -3,9, -10, null, 5], it can be expressed below this height balanced binary search tree:

 

 

② ideas

   I do not have good ideas, so see other people's answers, source: https: //leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/solution/xiang-xi-tong-su -de-si-lu-fen-xi-duo-jie-fa-by-24 /

   1, the binary search tree traversal sequence just array may output a ascending

   2. The reduction of a tree traversal sequence, thought of 105 questions and 106 issues, by preorder traversal added before or in sequence preorder traversal order to restore after adding a tree. Preamble (post-order) traversal role in it? Provide the root! The root node then, can be generated recursively

        Left and right subtrees.

       Here, there is only an ordered array, after no preamble or order traversal, how do you know the root of it? Balanced binary tree, if it wants to achieve balance, we selected as long as the root to the midpoint of the array.

③ Code

 1 class Solution {
 2     public TreeNode sortedArrayToBST(int[] nums) {
 3          return sortedArrayToBST(nums, 0, nums.length);
 4     }
 5 
 6     private TreeNode sortedArrayToBST(int[] nums, int start, int end) {
 7         if (start == end) {
 8             return null;
 9         }
10         int mid = (start + end) >>> 1;    //无符号右移一位,其实就是/2
11         TreeNode root = new new the TreeNode (the nums [MID]);     // the midpoint of the array elements as the root 
12 is          root.left = sortedArrayToBST (the nums, Start, MID);    // the current midpoint of the left half of this period as root.left 
13 is          = sortedArrayToBST root.right (the nums, MID +. 1, End);     // the current midpoint of the right half of this period as root.right 
14          return the root;
 15          }
 16 }

 

④ learned

    1, line 6 functions added, the third row of the called function, which increases the number of input parameters to 3, the system is only a function of the original input parameters.

    2, >>> unsigned right shift, and >>> 1 is divided by means of 2, i.e., / 2.

    3, how to create a node, as shown in line 11, such as 3 this number you want as a root node, then the write TreeNode root = new TreeNode (3) on the line.

    4, lines 12-13 feeling is a kind of dichotomy of usage, note that exit row 7.

Guess you like

Origin www.cnblogs.com/zf007/p/11641092.html