输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
Python
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
# write code here
if not root:
return []
if root and not root.left and not root.right and root.val == expectNumber:
return [[root.val]]
res = []
left = self.FindPath(root.left, expectNumber-root.val)
right = self.FindPath(root.right, expectNumber-root.val)
for i in left+right:
res.append([root.val]+i)
return res
Java
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target)
{
ArrayList<ArrayList<Integer>> resultLists = new ArrayList<>();
if(root == null)
return resultLists;
ArrayList<Integer> pathLists = new ArrayList<>();
int curSum = 0;
isTargetPath(root, target, resultLists, pathLists, curSum);
return resultLists;
}
public void isTargetPath(TreeNode root, int target, ArrayList<ArrayList<Integer>> resultLists, ArrayList<Integer> pathLists, int curSum)
{
if(root == null)
return;
curSum += root.val;
//如果是叶节点
if(root.left == null && root.right == null)
{
if(curSum == target)
{
pathLists.add(root.val);
resultLists.add(new ArrayList<Integer>(pathLists));
//在返回父节点之前,在路径上删除当前结点
pathLists.remove(pathLists.size()-1);
}
return;
}
pathLists.add(root.val);
isTargetPath(root.left, target, resultLists, pathLists, curSum);
isTargetPath(root.right, target, resultLists, pathLists, curSum);
pathLists.remove(pathLists.size()-1);
}
}
本文介绍了一种算法,用于寻找给定二叉树中所有节点值之和等于特定整数的路径。通过递归方法实现了Python和Java两种语言的解决方案。
283

被折叠的 条评论
为什么被折叠?



