Leetcode PHP題解--D97 783. Minimum Distance Between BST Nodes

D97 783. Minimum Distance Between BST Nodes

題目連接

783. Minimum Distance Between BST Nodesphp

題目分析

給定一個二叉樹,返回任意兩節點的最小差。node

思路

先獲取全部節點值,再逐個比對。不過這樣效率很低。this

最終代碼

<?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 TreeNode $root
     * @return Integer
     */
    function minDiffInBST($root) {
        $this->preOrder($root);
        $amount = count($this->values);
        $minValue = 9999999;
        for($i=0; $i<$amount; $i++){
            for($j=$i+1;$j<$amount; $j++){
                $diff = abs($this->values[$i] - $this->values[$j]);
                if($diff<$minValue){
                    $minValue = $diff;
                }
            }
        }
        return $minValue;
    }
    function preOrder($root){
        if(is_null($root->val)){
           return; 
        }
        $this->values[] = $root->val;
        if($root->left){
            $this->preOrder($root->left);
        }
        if($root->right){
            $this->preOrder($root->right);
        }
    }
}

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

相關文章
相關標籤/搜索