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

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

    原题链接:https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

    题目:给定一个升序排列元素的数组,将其转换成高度平衡的二叉树。

    思路:已经排序。则从中间劈开,中间元素为树的根,左右递归构建。

    	public TreeNode sortedArrayToBST(int[] num) {
    		return sortedArrayToBST(num,0,num.length - 1);
    	}
    	public TreeNode sortedArrayToBST(int[] num,int start,int end) {
    		if(start > end)
    			return null;
    		int mid = (start + end)/2;
    		TreeNode node = new TreeNode(num[mid]);
    		node.left = sortedArrayToBST(num,start,mid-1);
    		node.right = sortedArrayToBST(num,mid+1,end);
    		return node;
    	}
        // Definition for binary tree
        public class TreeNode {
            int val;
            TreeNode left;
            TreeNode right;
            TreeNode(int x) { val = x; }
        }


  • 相关阅读:
    测试报告M2
    11.24Daily Scrum(4)
    11.24Daily Scrum(3)
    11.24Daily Scrum(2)
    11.24Daily Scrum
    11.22Daily Scrum(2)
    11.22Daily Scrum
    Echarts中graph类型的运用求教
    Echarts学习求教
    用node编写自己的cli工具
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/5086914.html
Copyright © 2011-2022 走看看