zoukankan      html  css  js  c++  java
  • Convert Sorted Array to Binary Search Tree

    Convert Sorted Array to Binary Search Tree

    问题:

    Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

    思路:

      递归,dfs

    我的代码:

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode sortedArrayToBST(int[] num) {
            if(num == null || num.length == 0 )
                return null ;
            int len = num.length ;
            TreeNode rst = arrayToBST(num, 0, len - 1);
            return rst;
        }
        public TreeNode arrayToBST(int [] num, int left, int right)
        {
            if(left > right)    return null;
            if(left == right)   return new TreeNode(num[left]);
            int mid = (left + right)/2;
            TreeNode root = new TreeNode(num[mid]);
            root.left = arrayToBST(num, left, mid - 1);
            root.right = arrayToBST(num, mid + 1 , right);
            return root;
        }
    }
    View Code

    他人代码:

    public TreeNode sortedArrayToBST(int[] num) {
        if (num.length == 0) {
            return null;
        }
        TreeNode head = helper(num, 0, num.length - 1);
        return head;
    }
    
    public TreeNode helper(int[] num, int low, int high) {
        if (low > high) { // Done
            return null;
        }
        int mid = (low + high) / 2;
        TreeNode node = new TreeNode(num[mid]);
        node.left = helper(num, low, mid - 1);
        node.right = helper(num, mid + 1, high);
        return node;
    }
    View Code

    学习之处:

    • 我的代码有冗余的地方 left == right的判断可以省去
  • 相关阅读:
    nginx 中用 sed 批量增加配置文件内容
    apache中 sed 指定文件中某字符串增加行
    centos7 下 nfs 搭建总结
    centos7.2 环境下两个数据库的安装部署
    centos7.2 环境下 mysql-5.1.73 安装配置
    二代云盒混合网
    安装tftp
    云盒所有服务检查
    将某个目录下的 文件(字符窜) 只将数字过滤出来
    让VS2012支持Less css
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4318681.html
Copyright © 2011-2022 走看看