leetcode 108 and leetcode 109

// thoughts: Sometimes ah, for a title, if you know where that point, will be very simple, such as these two questions, the orderly array into a binary search tree,

There are a few points:

1. binary search tree: For a node, the node is less than its left it, it's right node is greater than it, this is the nature of the binary search tree, So we can draw a conclusion: in order to traverse the tree we can find an array must be ordered from small to large, because the preorder is the first left node ---> root -----> right node, it is ordered.

2. For a binary search tree, we can easily be converted into an ordered array, but in turn it? How to convert an ordered array of binary search trees?

The question becomes if we find the root after the conversion, with the root, the root element of the array that is left of the left sub-tree, and on the right is the right subtree, then recursively down into the left, right recursion they get the root node that is left on the floor, right node is recursive in the end like this, in the end termination condition is to find the elements of the interval does not exist, return null like.

3. For the root key is who is it?

I do not know, they say that with the midpoint of the corresponding elements as the root node, I do not know how to prove there is to know little friends are welcome message to tell me.

According to this idea,

code show as below:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public TreeNode sortedArrayToBST(int[] nums) {
12         if(nums==null||nums.length==0)
13             return null;
14         return helper(nums,0,nums.length-1);
15     }
16     public TreeNode helper(int[] nums,int l,int r)
17     {
18         if(l>r)
19             return null;
20         int mid=l+(r-l)/2;
21         TreeNode root=new TreeNode(nums[mid]);
22         root.left=helper(nums,l,mid-1);
23         root.right=helper(nums,mid+1,r);
24         return root;
25     }
26 }

Guess you like

Origin www.cnblogs.com/cold-windy/p/11779244.html