日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

【剑指offer】面试题34:二叉树中和为某一值的路径

發(fā)布時(shí)間:2024/7/19 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【剑指offer】面试题34:二叉树中和为某一值的路径 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

輸入一顆二叉樹(shù)和一個(gè)整數(shù),打印出二叉樹(shù)中結(jié)點(diǎn)值的和為輸入整數(shù)的所有路徑。路徑定義為從樹(shù)的根結(jié)點(diǎn)開(kāi)始往下一直到葉結(jié)點(diǎn)所經(jīng)過(guò)的結(jié)點(diǎn)形成一條路徑。

代碼:

package offer;

import java.util.ArrayList;

class BineryTree1
{
?? ?int val;
?? ?BineryTree1 left = null;
?? ?BineryTree1 right = null;
?? ?BineryTree1(int val)
?? ?{
?? ??? ?this.val = val;
?? ?}
}
public class ti34 {
?? ?static ArrayList<Integer> list = new ArrayList<Integer>();
?? ?static ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
?? ?static ?ArrayList<ArrayList<Integer>> FindPath(BineryTree1 root,int target)
?? ?{
?? ??? ?
?? ??? ?if(root==null)
?? ??? ?{
?? ??? ??? ?return result;
?? ??? ?}
?? ??? ?list.add(root.val);
?? ??? ?target-=root.val;
?? ??? ?if(target == 0 && root.left == null && root.right == null) {
? ? ? ? ?? ?result.add(new ArrayList<Integer>(list) );//重點(diǎn),這里一定要強(qiáng)制new一個(gè)對(duì)象,要不然不行
? ? ? ? }
?? ??? ?FindPath(root.left,target);
?? ??? ?FindPath(root.right,target);
?? ??? ?list.remove(list.size()-1);
?? ??? ?return result;
?? ?}
?? ?public static void main(String[] args)
?? ?{
?? ??? ?BineryTree1 a = new BineryTree1(10);
?? ??? ?BineryTree1 b = new BineryTree1(5);
?? ??? ?BineryTree1 c = new BineryTree1(12);
?? ??? ?BineryTree1 d = new BineryTree1(4);
?? ??? ?BineryTree1 e = new BineryTree1(7);
?? ??? ?a.left = b;
?? ??? ?a.right = c;
?? ??? ?b.left = d;
?? ??? ?b.right = e;
?? ??? ?ArrayList<ArrayList<Integer>> list = FindPath(a,22);
?? ??? ?for(int i=0;i<list.size();i++)
?? ??? ?{
?? ??? ??? ?for(int j=0;j<list.get(i).size();j++)
?? ??? ??? ?{
?? ??? ??? ??? ?System.out.print(list.get(i).get(j)+" ");
?? ??? ??? ?}
?? ??? ??? ?System.out.println();
?? ??? ?}
?? ?}
}
?

總結(jié)

以上是生活随笔為你收集整理的【剑指offer】面试题34:二叉树中和为某一值的路径的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。