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