zoukankan      html  css  js  c++  java
  • Cracking the Coding Interview 4.8

    You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum up to that value. Note that it can be any path in the tree-it does not have to start at the root.

    思路:

    既然路径的开始不一定在根,那么找出从根开始的所有路径就不够了。每个节点都有可能是开始,也有可能是结束。将任一节点当做结束节点,倒推至根节点,路径上只要有和为value,就是一个满足的路径,但是找到一个还不能停,一直要倒推到根为止,因为可能倒推序列是2+3-1+1,如果value是5,那么2+3满足,但2+3-1+1也满足,因此我们一直要倒推到根,才能找出所有的路径。

    void func(Node *n,int *buf,int level,int sum)//n是结束节点,buf里存放了从该节点到根每个节点上的key,level是深度,sum是要求的和
    {
        if(n == NULL)
        {
            return;
        }
        buf[level]=n->key;
        int temp = sum;
        for(int i=level;i>=0;i--)
        {
            temp-=buf[i];
            if(temp==0)
            {
                for(int j=i;j<level;j++)
                {
                    printf("%d,",buf[j]);
                }
                printf("%d
    ",buf[level]);
            }
        }
        func(n->left,buf,level+1,sum);
        func(n->right,buf,level+1,sum);
    }
  • 相关阅读:
    CentOS/Ubuntu安装最新的gcc-9
    CentOS 7 源码安装 CMake 3.16.2 最新稳定版。解决 cmake: command not found 问题
    堆排序
    linux可重入、异步信号安全和线程安全
    目录
    教程文档
    推荐文章
    学习文档
    开发工具-索引
    同步/异步/阻塞/非阻塞
  • 原文地址:https://www.cnblogs.com/johnsblog/p/3984255.html
Copyright © 2011-2022 走看看