二叉树-在二叉树中找到累加和为指定值的最长路径长度

//在二叉树中找到累加和为指定值的最长路径长度
public class Node{
    public int value;
    public Node left;
    public Node right;

    public Node(int data){
        this.value=data;
    }
}

public int getMaxlength(Node head,int sum){
    HashMap<Integer,Integer> sumMap=new HashMap<Integer,Integer>();
    sumMap.put(0,0);
    return preOrder(head,sum,0,1,0,sumMap);
}
public int preOrder(Node head,int sum,int preSum,int level,int maxLen,HashMap<Integer,Integer> sumMap){
    if(head==null){
        return maxLen;
    }
    int curSum=preSum+head.value;
    if(!sumMap.containsKey(curSum)){
        sumMap.put(curSum,level);
    }
    if(sumMap.containsKey(curSum-sum)){
        maxLen=Math.max(level-sumMap.get(curSum-sum),maxLen);
    }
    maxLen=preOrder(head.left,sum,curSum,level+1,maxLen,sumMap);
    maxLen=preOrder(head.right,sum,curSum,level+1,maxLen,sumMap);
    if(level==sumMap.get(curSum)){
        sumMap.remove(curSum);
    }
    return maxLen;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用C语言实现在二叉树找出和为某一的所有路径的示例代码: ```c #include <stdio.h> #include <stdlib.h> typedef struct TreeNode { int val; struct TreeNode* left; struct TreeNode* right; } TreeNode; void findPath(TreeNode* root, int sum, int* path, int depth) { if (root == NULL) { return; } path[depth] = root->val; int i, curSum = 0; for (i = depth; i >= 0; --i) { curSum += path[i]; if (curSum == sum) { int j; for (j = i; j < depth; ++j) { printf("%d->", path[j]); } printf("%d\n", path[depth]); } } findPath(root->left, sum, path, depth + 1); findPath(root->right, sum, path, depth + 1); } int main() { // 构造二叉树 TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode)); root->val = 10; root->left = (TreeNode*)malloc(sizeof(TreeNode)); root->left->val = 5; root->right = (TreeNode*)malloc(sizeof(TreeNode)); root->right->val = 12; root->left->left = (TreeNode*)malloc(sizeof(TreeNode)); root->left->left->val = 4; root->left->right = (TreeNode*)malloc(sizeof(TreeNode)); root->left->right->val = 7; // 在二叉树查找和为22的路径 int path[100]; findPath(root, 22, path, 0); // 释放二叉树空间 free(root->left->left); free(root->left->right); free(root->left); free(root->right); free(root); return 0; } ``` 该示例代码,我们先构造了一棵二叉树,并在其查找和为22的路径。在查找路径的过程,我们使用了深度优先遍历的方法,通过一个数组来保存当前已经走过的路径,每次遍历到一个节点,则将该节点的加入路径。在加入之后,我们检查路径是否存在和为目标的子路径,如果存在,则输出该路径。最后,我们递归遍历该节点的左子树和右子树,以便查找所有可能的路径。 需要注意的是,该示例代码并未考虑二叉树存在负数的情况,如有需要,可以根据实际情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值