Leetcode基础刷题之PHP解析(108,513)

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

2 0 1 9 -5 -7   期二    

Leetcode基础刷题之 PHP 解析(98. Validate Binary Search Tree)

Leetcode基础刷题之PHP解析(108,513)

给定一个升序的数组,转换为高度平衡的二叉查找树。

因为二叉查找树的中序遍历就是一个升序的数组,所以对于升序数组来说,我们只要找到它的中间点,就是二叉查找树的根,那么它的左右子树必然也是这个道理。

/**
 * 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;
    }
}

Leetcode基础刷题之PHP解析(108,513)

给定一个二叉树,找出树最后一层最左边的结点值。

使用层进行遍历,每个层从右往左遍历,这样就能保证我们最后输出的一定是 最后一层的最左结点。

/**
 * 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


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

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

Web Security Testing Cookbook

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》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换