|
導(dǎo)讀網(wǎng)頁的本質(zhì)就是超級(jí)文本標(biāo)記語言,通過結(jié)合使用其他的Web技術(shù)(如:腳本語言、公共網(wǎng)關(guān)接口、組件等),可以創(chuàng)造出功能強(qiáng)大的網(wǎng)頁。因而,超級(jí)文本標(biāo)記語言是萬維網(wǎng)(Web)編程的基礎(chǔ),也就是說萬維網(wǎng)是建立... 網(wǎng)頁的本質(zhì)就是超級(jí)文本標(biāo)記語言,通過結(jié)合使用其他的Web技術(shù)(如:腳本語言、公共網(wǎng)關(guān)接口、組件等),可以創(chuàng)造出功能強(qiáng)大的網(wǎng)頁。因而,超級(jí)文本標(biāo)記語言是萬維網(wǎng)(Web)編程的基礎(chǔ),也就是說萬維網(wǎng)是建立在超文本基礎(chǔ)之上的。超級(jí)文本標(biāo)記語言之所以稱為超文本標(biāo)記語言,是因?yàn)槲谋局邪怂^“超級(jí)鏈接”點(diǎn)。 本篇文章給大家?guī)淼膬?nèi)容是關(guān)于php如何實(shí)現(xiàn)二叉樹中和為某一值的路徑(代碼),有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對(duì)你有所幫助。二叉樹中和為某一值的路徑: 輸入一顆二叉樹的跟節(jié)點(diǎn)和一個(gè)整數(shù),打印出二叉樹中結(jié)點(diǎn)值的和為輸入整數(shù)的所有路徑。路徑定義為從樹的根結(jié)點(diǎn)開始往下一直到葉結(jié)點(diǎn)所經(jīng)過的結(jié)點(diǎn)形成一條路徑。(注意: 在返回值的list中,數(shù)組長(zhǎng)度大的數(shù)組靠前) 思路: 1、二叉樹的前序遍歷,中左右順序 2、把目標(biāo)值target傳進(jìn)去,target-=val 3、target為0并且left和right都為null,達(dá)到葉結(jié)點(diǎn) 4、函數(shù)外部?jī)蓚(gè)數(shù)組,list數(shù)組存一條路徑,listAll數(shù)組存所有路徑 FindPath(root,target)
if root==null return listAll
list[]=root.val
target-=root.val
if target==0 && root->left==null && root->right==null
listAll[]=list
FindPath(root->left,target)
FindPath(root->right,target)
//如果到了這條路徑的跟結(jié)點(diǎn),并沒有達(dá)到目標(biāo),就刪掉最后的結(jié)點(diǎn),退回上一個(gè)結(jié)點(diǎn)
array_pop(list)
return listAll<?php
class TreeNode{
var $val;
var $left = NULL;
var $right = NULL;
function __construct($val){
$this->val = $val;
}
}
function FindPath($root,$target)
{
static $list=array();
static $listAll=array();
if($root==null){
return $listAll;
}
$target-=$root->val;
$list[]=$root->val;
if($target==0 && $root->left==null && $root->right==null){
$listAll[]=$list;
}
FindPath($root->left,$target);
FindPath($root->right,$target);
array_pop($list);
return $listAll;
}
$node10=new TreeNode(10);
$node5=new TreeNode(5);
$node12=new TreeNode(12);
$node4=new TreeNode(4);
$node7=new TreeNode(7);
$node10->left=$node5;
$node10->right=$node12;
$node5->left=$node4;
$node5->left=$node7;
$tree=$node10;
$res=FindPath($tree,22);
var_dump($res);<?php
/*class TreeNode{
var $val;
var $left = NULL;
var $right = NULL;
function __construct($val){
$this->val = $val;
}
}*/
function FindPath($root,$target)
{
$list=array();
$listAll=array();
$res=dfs($root,$target,$list,$listAll);
return $res;
}
function dfs($root,$target,&$list,&$listAll)
{
if($root==null){
return $listAll;
}
$target-=$root->val;
$list[]=$root->val;
if($target==0 && $root->left==null && $root->right==null){
$listAll[]=$list;
}
dfs($root->left,$target,$list,$listAll);
dfs($root->right,$target,$list,$listAll);
array_pop($list);
return $listAll;
}以上就是php如何實(shí)現(xiàn)二叉樹中和為某一值的路徑(代碼)的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注php中文網(wǎng)其它相關(guān)文章! 網(wǎng)站建設(shè)是一個(gè)廣義的術(shù)語,涵蓋了許多不同的技能和學(xué)科中所使用的生產(chǎn)和維護(hù)的網(wǎng)站。 |
溫馨提示:喜歡本站的話,請(qǐng)收藏一下本站!