1. 程式人生 > >Leetcode PHP題解--D89 653. Two Sum IV

Leetcode PHP題解--D89 653. Two Sum IV

D89 653. Two Sum IV - Input is a BST

題目連結

653. Two Sum IV - Input is a BST

題目分析

給定一個二叉樹以及一個目標數字,判斷能不能通過二叉樹中任意兩個節點的值相加得到。

思路

思路1

遍歷的時候,先把節點存起來,並且與每一個值相加,判斷是否等於所需值。

這個演算法很明顯效率比較低。

思路2

遍歷的時候,把自身作為鍵存進陣列內。用isset函式判斷與所求數字之差是否在陣列內。存在既返回。否則,遍歷子節點。

最終程式碼

<?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 {
    protected $has = [];
    protected $hasResult = false;
    /**
     * @param TreeNode $root
     * @param Integer $k
     * @return Boolean
     */
    function findTarget($root, $k) {
        if(is_null($root)){
            return;
        }
        if(isset($this->has[$k-($root->val)])){
            $this->hasResult = true;
            return $this->hasResult;
        }
        else{
            $this->has[$root->val] = true;
            if(!$this->findTarget($root->left, $k)){
                $this->findTarget($root->right, $k);
            }
        }
        return $this->hasResult;
    }
}

若覺得本文章對你有用,歡迎用