Leetcode PHP题解--D95 108. Convert Sorted Array to Binary Search Tree

栏目: PHP · 发布时间: 4年前

内容简介:给定一个顺序数组,将其装换成平衡二叉树。首先讲数组分成两半,左边的元素为左子树的内容,右边为右子树内容。

D95 108. Convert Sorted Array to Binary Search Tree

题目链接

108. Convert Sorted Array to Binary Search Tree

题目分析

给定一个顺序数组,将其装换成平衡二叉树。

思路

首先讲数组分成两半,左边的元素为左子树的内容,右边为右子树内容。

中间的元素作为当前节点的值。

若左边的元素个数大于0,则递归该进程。

右边同理。

返回当前节点即可。

最终代码

<?php
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($value) { $this->val = $value; }
 * }
 */
class Solution {
    /**
     * @param Integer[] $nums
     * @return TreeNode
     */
    function sortedArrayToBST($nums) {
        $len = count($nums);
        $mid = floor($len/2);
        $leftPart = array_slice($nums, 0, $mid);
        $root = new TreeNode($nums[$mid]);
        $rightPart = array_slice($nums, $mid+1);

        if(count($leftPart)){
            $root->left  = $this->sortedArrayToBST($leftPart);
        }
        if(count($rightPart)){
            $root->right  = $this->sortedArrayToBST($rightPart);
        }
        return $root;
    }
}

若觉得本文章对你有用,欢迎用 爱发电 资助。


以上所述就是小编给大家介绍的《Leetcode PHP题解--D95 108. Convert Sorted Array to Binary Search Tree》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

HTML5

HTML5

Matthew David / Focal Press / 2010-07-29 / USD 39.95

Implement the powerful new multimedia and interactive capabilities offered by HTML5, including style control tools, illustration tools, video, audio, and rich media solutions. Understand how HTML5 is ......一起来看看 《HTML5》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具