【剑指offer】面试题34:二叉树中和为某一值的路径
輸入一顆二叉樹(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)題。
- 上一篇: 第一范式,第二范式,第三范式,BCNF范
- 下一篇: Leetcode--80. 删除排序数组