java-4.-在二元树中找出和为某一值的所有路径 .

本文介绍了一种使用双向链表来存储路径的方法,在遍历树结构过程中寻找满足特定和的子树路径。当节点不再作为路径的一部分时,可以删除该节点。具体实现包括递归地在左子树和右子树中查找,同时更新当前路径和路径总和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


/*
* 0.use a TwoWayLinkedList to store the path.when the node can't be path,you should/can delete it.
* 1.curSum==exceptedSum:if the lastNode is TreeNode,printPath();delete the node otherwise
* 2.curSum>exceptedSum:return;
* 3.curSum<exceptedSum:push the node to path,continue in LeftTree and RightTree
*/
public void findSubTree(Node curNode,int exceptedSum){
Node pathNode=null;
int curSum=0;
findSubTreeHelp(curNode,pathNode,curSum,exceptedSum);
}
public void findSubTreeHelp(Node curNode,Node pathNode,int curSum,int exceptedSum){
curSum+=curNode.getVal();
if(curSum>exceptedSum){
return;
}
Node newNode=new Node(curNode.getVal());
if(pathNode==null){
pathNode=newNode;
}else{
pathNode.right=newNode;
newNode.left=pathNode;
pathNode=newNode;
}
if(curSum==exceptedSum){
if(curNode.getLeft()==null&&curNode.getRight()==null){
printPath(pathNode);
}else{
pathNode=deletePathNode(pathNode);
}
}
if(curSum<exceptedSum){
if(curNode.getLeft()!=null){
findSubTreeHelp(curNode.getLeft(),pathNode,curSum,exceptedSum);
}
if(curNode.getRight()!=null){
findSubTreeHelp(curNode.getRight(),pathNode,curSum,exceptedSum);
}
}
}
public Node deletePathNode(Node node){
Node pathNode=node.getLeft();
pathNode.right=null;
return pathNode;
}
public void printPath(Node node){
if(node==null)return;
while(node.getLeft()!=null){
node=node.getLeft();
}
while(node!=null){
System.out.print(node.getVal()+",");
node=node.getRight();
}
System.out.println();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值