zoukankan      html  css  js  c++  java
  • leetcode 108 和leetcode 109

    //感想:有时候啊,对于一道题目,如果知道那个点在哪,就会非常简单,比如说这两题,将有序的数组转换为二叉搜索树,

    有几个点:

    1.二叉搜索树:对于某个节点,它的左节点小于它,它的右节点大于它,这是二叉搜索树的性质,所以呢我们又可以得出一个结论:中序遍历这个树,我们就可以发现一定是有序的数组,从小到大,因为中序遍历就是先左节点--->根节点----->右节点,所以是有序的。

    2.对于一个二叉搜索树我们可以很方便的转换成有序数组,但是反过来呢?怎么将一个有序数组转换成二叉搜索树呢?

    问题的关键变成了如果找到我们转换后的根节点,根节点有了,那数组中根节点左边的元素就是左子树了,右边的就是右子树,然后再往下递归进入左边,右边递归得到它们的根节点即上一层的左节点,右节点,就是这样递归到底就好了,到底的终止条件就是查找的区间不存在元素了,返回null就好。

    3.对于关键就是谁是根节点呢?

    我也不知道,他们说用中点对应的元素作为根节点,我不知道怎么证明,有知道的小伙伴欢迎留言告诉我。

    按照这个思路,

    代码如下:

     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 }
  • 相关阅读:
    CF1290E Cartesian Tree
    【LeetCode】11. 盛最多水的容器
    【LeetCode】10. 正则表达式匹配
    【LeetCode】9. 回文数
    【LeetCode】8. 字符串转换整数 (atoi)
    【LeetCode】7. 整数反转
    【LeetCode】6. Z 字形变换
    【LeetCode】5. 最长回文子串
    【LeetCode】4. 寻找两个正序数组的中位数[待补充]
    【LeetCode】3. 无重复字符的最长子串
  • 原文地址:https://www.cnblogs.com/cold-windy/p/11779244.html
Copyright © 2011-2022 走看看