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

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

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        
        public TreeNode creatBST(int low,int high,int[] num) {
            if(low<=high) {
                int mid = (low+high)/2;
                TreeNode root = new TreeNode(num[mid]);
                root.left = creatBST(low,mid-1,num);
                root.right = creatBST(mid+1,high,num);
                return root;
            }
            else return null;
        }
        
        public TreeNode sortedArrayToBST(int[] num) {
            return creatBST(0,num.length-1,num);
        }
    }
  • 相关阅读:
    敏捷软件开发实践-Code Review Process(转)
    随笔1
    随笔
    随笔
    低级错误
    随笔
    随笔2
    随笔
    这以前写的代码
    蛋疼的vs
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4420264.html
Copyright © 2011-2022 走看看