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

xiaoxiao2021-02-28  87

题目描述

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

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(); } } }

转载请注明原文地址: https://www.6miu.com/read-97044.html

最新回复(0)