剑指offer:二叉树中和为某一值的路径

题目描述

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

1.递归版本1

参考牛客网网友笔记

import java.util.*;
public class Solution {
    ArrayList<ArrayList<Integer>> listAll=new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> list=new ArrayList<Integer>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        if(root==null)	return listAll;
        list.add(root.val);
        target-=root.val;
        if(target==0&&root.left==null&&root.right==null){
            listAll.add(new ArrayList<Integer>(list));
        }
        FindPath(root.left,target);
        FindPath(root.right,target);
        list.remove(list.size()-1);
        return listAll;
    }
}

2.递归版本2

参考牛客网网友回答


public class Solution {
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        ArrayList<ArrayList<Integer>> paths=new ArrayList<ArrayList<Integer>>();
        if(root==null)return paths;
        find(paths,new ArrayList<Integer>(),root,target);
        return paths;
    }
    public void find(ArrayList<ArrayList<Integer>> paths,ArrayList<Integer> path,TreeNode root,int target){
        path.add(root.val);
        if(root.left==null&&root.right==null){
            if(target==root.val){
                paths.add(path);
            }
            return;
        }
        ArrayList<Integer> path2=new ArrayList<>();
        path2.addAll(path);
        if(root.left!=null)find(paths,path,root.left,target-root.val);
        if(root.right!=null)find(paths,path2,root.right,target-root.val);
    }
}

3.非递归版本

参考牛客网网友回答

import java.util.ArrayList;
import java.util.Stack;

public class Solution {
	public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
		ArrayList<ArrayList<Integer>> pathList = new ArrayList<ArrayList<Integer>>();
		if (root == null)
			return pathList;
		Stack<Integer> stack = new Stack<Integer>();
		FindPath(root, target, stack, pathList);
		return pathList;
	}

	private void FindPath(TreeNode root, int target, Stack<Integer> path, ArrayList<ArrayList<Integer>> pathList) {
		if (root == null)
			return;
		if (root.left == null && root.right == null) {
			if (root.val == target) {
				ArrayList<Integer> list = new ArrayList<Integer>();
				for (int i : path) {
					list.add(new Integer(i));
				}
				list.add(new Integer(root.val));
				pathList.add(list);
			}
		} else {
			path.push(new Integer(root.val));
			FindPath(root.left, target - root.val, path, pathList);
			FindPath(root.right, target - root.val, path, pathList);
			path.pop();
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值