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

D95 108. Convert Sorted Array to Binary Search Tree

題目連接

108. Convert Sorted Array to Binary Search Treephp

題目分析

給定一個順序數組,將其裝換成平衡二叉樹。node

思路

首先講數組分紅兩半,左邊的元素爲左子樹的內容,右邊爲右子樹內容。數組

中間的元素做爲當前節點的值。this

若左邊的元素個數大於0,則遞歸該進程。.net

右邊同理。code

返回當前節點便可。遞歸

最終代碼

<?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;
    }
}

若以爲本文章對你有用,歡迎用愛發電資助。進程

相關文章
相關標籤/搜索