最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

php實(shí)現(xiàn)二叉樹中和為某一值的路徑方法

 更新時(shí)間:2018年10月14日 14:50:07   投稿:laozhang  
在本篇文章中我們給大家分享了php實(shí)現(xiàn)二叉樹中和為某一值的路徑方法,有需要的朋友們可以參考下。

二叉樹中和為某一值的路徑:

輸入一顆二叉樹的跟節(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;

}

以上就是本次內(nèi)容的全部實(shí)例代碼,大家可以本次測(cè)試一下,感謝大家對(duì)腳本之家的支持。

相關(guān)文章

最新評(píng)論

崇州市| 海阳市| 治县。| 延庆县| 阿拉善左旗| 鄂尔多斯市| 都匀市| 天全县| 五华县| 南昌县| 泗水县| 鞍山市| 和静县| 陕西省| 东明县| 齐齐哈尔市| 吕梁市| 囊谦县| 南乐县| 庄河市| 福泉市| 滁州市| 阜康市| 临朐县| 改则县| 蒲江县| 永和县| 松滋市| 阳城县| 红安县| 叶城县| 新昌县| 潼南县| 邳州市| 中方县| 东乌| 新乡市| 庄浪县| 虹口区| 柳江县| 白河县|