Leetcode PHP題解--D95 108. Convert Sorted Array to Binary Search Tree
阿新 • • 發佈:2019-06-29
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; } }