import java.util.ArrayList;
import java.util.Stack;
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class Solution {
ArrayList<ArrayList<Integer>> Arraylist=new ArrayList<>();
ArrayList<Integer>list=new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root==null){
return Arraylist;
}
list.add(root.val);
target-=root.val;
//找到一条路径则加入路径的集合
if(target==0&&root.left==null&&root.right==null)
{
Arraylist.add(new ArrayList<Integer>(list));
}
if(root.left!=null)
{
FindPath(root.left,target);
}
if(root.right!=null)
{
FindPath(root.right,target);
}
list.remove(list.size()-1);//删除叶节点,回退
return Arraylist;
}
//二叉树的深度遍历
public void DFS(TreeNode node)
{
if(node==null)
{
return ;
}
Stack<TreeNode>stack=new Stack<>();
stack.push(node);
while(!stack.isEmpty())
{
TreeNode tmp=stack.pop();
System.out.print(tmp.val+" ");
if(tmp.left!=null)
{
DFS(tmp.left);
}
if(tmp.right!=null)
{
DFS(tmp.right);
}
}
}
public static void main(String[]args){
//System.out.println("Hello");
TreeNode root=new TreeNode(1);
root.left=new TreeNode(2);
root.right=new TreeNode(3);
root.left.left=new TreeNode(4);
root.left.right=new TreeNode(5);
root.right.left=new TreeNode(6);
root.right.right=new TreeNode(7);
Solution s=new Solution();
s.FindPath(root,7);
}
}
二叉树中和为某一值的路径
最新推荐文章于 2025-03-25 10:51:28 发布