2 0 1 9 -5 -7 星 期二 开 始 吧
上 一 题 链 接 Leetcode基础刷题之 PHP 解析(98. Validate Binary Search Tree)
题 目 描 述
给定一个升序的数组,转换为高度平衡的二叉查找树。
题 目 分 析
因为二叉查找树的中序遍历就是一个升序的数组,所以对于升序数组来说,我们只要找到它的中间点,就是二叉查找树的根,那么它的左右子树必然也是这个道理。
/**
* 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) {
return $this->buildTree($nums,0,count($nums)-1);
}
function buildTree($nums,$l,$r){
if($l>$r){
return ;
}
$middle=floor(($l+$r)/2);
$node=new TreeNode($nums[$middle]);
$node->left=$this->buildTree($nums,$l,$middle-1);
$node->right=$this->buildTree($nums,$middle+1,$r);
return $node;
}
}
给定一个二叉树,找出树最后一层最左边的结点值。
题 目 分 析
使用层进行遍历,每个层从右往左遍历,这样就能保证我们最后输出的一定是 最后一层的最左结点。
/**
* 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 TreeNode $root
* @return Integer
*/
function findBottomLeftValue($root) {
$data=[];
array_unshift($data,$root);
while(!empty($data)){
$node=array_shift($data);
if($node->right !=null) array_push($data,$node->right);
if($node->left !=null) array_push($data,$node->left);
}
return $node->val;
}
}
树的题目到这里告一段落了
Github整理地址:https://github.com/wuqinqiang/leetcode-php
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- Apache Flink 零基础入门(一):基础概念解析
- Apache Flink 零基础入门(一):基础概念解析
- JStorm 源码解析:基础线程模型
- React Hooks 解析(上):基础
- TypeScript基础入门之模块解析(一)
- TypeScript基础入门之模块解析(二)
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Web Security Testing Cookbook
Paco Hope、Ben Walther / O'Reilly Media / 2008-10-24 / USD 39.99
Among the tests you perform on web applications, security testing is perhaps the most important, yet it's often the most neglected. The recipes in the Web Security Testing Cookbook demonstrate how dev......一起来看看 《Web Security Testing Cookbook》 这本书的介绍吧!