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

如何在二叉树中找出和为某一值的所有路径 本篇文章是对在二叉树中找出和为某一值的所有路径方法进行了详细的分析介绍,需要的朋友参考下 立即下载

 

题目:输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。
例如输入整数22和如下二元树
                                             10
                                            /    \
                                           5      12
                                         /    \   
                                      4      7  
则打印出两条路径:10, 12和10, 5, 7。
分析:这是百度的一道笔试题,考查对树这种基本数据结构以及递归函数的理解。
当访问到某一结点时,把该结点添加到路径上,并累加当前结点的值。如果当前结点为叶结点并且当前路径的和刚好等于输入的整数,则当前的路径符合要求,我们把它打印出来。如果当前结点不是叶结点,则继续访问它的子结点。当前结点访问结束后,递归函数将自动回到父结点。因此我们在函数退出之前要在路径上删除当前结点并减去当前结点的值,以确保返回父结点时路径刚好是根结点到父结点的路径。我们不难看出保存路径的数据结构实际上是一个栈结构,因为路径要与递归调用状态一致,而递归调用本质就是一个压栈和出栈的过程。
参考代码:


#include <iostream>
using namespace std;
#include <deque>
using std::deque;

template<typename T>
struct Node
{
public:
    Node(T value);
    T getValue ();
    Node *getLeftChld ();
    Node *getRightChild ();
    void setLeftChild (Node *leftChild);
    void setRightChild (Node *rightChild);
private:
    T mValue;
    Node *mLeftChild;
    Node *mRightChild;
};

template<typename T>
Node<T>::Node (T value):mValue(value),mLeftChild(0),mRightChild(0)
{
}

template<typename T>
T
Node<T>::getValue()
{
    return mValue;
}

template<typename T>
Node<T>*
Node<T>::getLeftChld()
{
    return mLeftChild;
}

template<typename T>
Node<T>*
Node<T>::getRightChild()
{
    return mRightChild;
}

template<typename T>
void
Node<T>::setLeftChild(Node *leftChild)
{
    mLeftChild = leftChild;
}

template<typename T>
void
Node<T>::setRightChild(Node *rightChild)
{
    mRightChild = rightChild;
}

Node<int> *
buildTree()
{
    Node<int> *r10 = new Node<int>(10);
    Node<int> *r4 = new Node<int>(4);
    Node<int> *r5 = new Node<int>(5);
    Node<int> *r7 = new Node<int>(7);
    Node<int> *r12 = new Node<int>(12);
    r10->setLeftChild(r5);
    r10->setRightChild(r12);
    r5->setLeftChild(r4);
    r5->setRightChild(r7);
    return r10;
}

template<typename T>
void
getTheValue(Node<T> *node,T expectValue, T & currentValue,deque<T> &path)
{
    T nodeValue = node->getValue();
    currentValue += nodeValue;
    path.push_back(node->getValue());
    bool isLeaf = (0 == node->getLeftChld()) && (0 == node->getRightChild());
    if ( (currentValue == expectValue) && isLeaf)
    {
        for ( int i = 0 ; i < path.size(); i ++ )
        {
            cout << path[i]<<" ";
        }
        cout << endl;
    }
    if ( node ->getLeftChld() )
    {
        getTheValue(node->getLeftChld(),expectValue,currentValue,path);
    }
    if ( node ->getRightChild() )
    {
        getTheValue(node->getRightChild(),expectValue,currentValue,path);
    }
    path.pop_back();
    currentValue -= nodeValue;
}

int main(int argc,char *argv[])
{
    Node<int> *result = buildTree();
    int currentValue = 0;
    deque<int> path;
    getTheValue<int>(result,22,currentValue,path);
    return 0;
}


        
Cursor概述及环境配置 Cursor 是一款基于 AI 的代码编辑器,支持 VS Code 配置迁移和 Java 开发环境配置。主要功能分为 Cursor Settings(AI 相关设置)和 Editor Settings(基础编辑器设置)。用户可通过一键导入或手动方式迁移 VS Code 配置,配置包括主题、扩展和快捷键等。对于 Java 开发,需配置 JDK 和 Maven 路径,并安装 Java 扩展插件以获得完整开发体验,如代码补全、调试和 Maven 项目管理。此外,Cursor 支持汉化配置,用户可安装中文语言包切换 阅读详情

相关推荐

Jetson Orin Nano GPIO 实战,用 devmem 玩转 Pinmux 引脚复用配置

devmem 是一个直接读写寄存器的工具,通过 mmap 将 /dev/mem 中的物理地址区域映射到用户空间进程地址空间,从而实现直接读写,正常情况下在 /dev 下可以看到 mem。可以看到对应 bit5 bit6 分别为 1,对应配置为 E_IO_HV 为 ENABLE 以及 E_INPUT 为 ENABLE。需要 TRM 手册查看相关寄存器,以及安装 busybox,busybox 内置了 devmem。根据 TRM 手册,找到 I2C_SDA 的 pinmux 地址偏移是 0x18。

darcsdn 1643

剑指 Offer 34. 二叉树中和为某一值的路径(C++) 回溯法+先序遍历

输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。 示例: 给定如下二叉树,以及目标和 sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 返回: [ [5,4,11,2], [5,8,4,5] ] 提示: 节点总数 <= 10000 注意:本题与主站 113 题相同:https

伍粟的博客 311

五、2K0300 久久派开发板的GPIO控制与Shell脚本自动化实战

本文详细介绍了基于龙芯2K0300处理器的久久派开发板的GPIO控制方法,通过sysfs文件系统实现LED控制和传感器读取。重点讲解了Shell脚本自动化实战,包括LED闪烁、流水灯效果和传感器数据采集,为物联网项目开发提供完整解决方案。

silver的专栏 687

在二元树中找出和为某一值的所有路径(根节点到任一节点的路径)

题目:输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。 例如输入整数22和如下二元树                                             10                                            /   \              

diudiuyoung的专栏 503

408计算机复试专业课问答汇总

408计算机复试专业课问答汇总

weixin_45930223的博客 3698

面试篇 - LoRA(Low-Rank Adaptation) 原理

输出示例:trainable params: 262,144 || all params: 6,742,016,000 || trainable%: 0.0039。论文实验显示:零初始化 BB 可使初始损失与预训练模型相差不足0.1%,而非零初始化可能差50%+。若初始 ΔW≠0,模型可能立即偏离预训练学到的知识(如GPT-3突然忘记如何造句)。:如同汽车改装,先保持原厂配置(W),再逐步加装新部件(ΔW),避免直接飙车失控。:大模型的权重变化矩阵 ΔWΔW 通常是低秩的(少数主成分主导变化)。

qq_60245590的博客 1151

在二叉树中找出和为某一值的所有路径

路径的起点为根节点,如        10                                                 /   \                                               5    12                                            /  \

bnufq的专栏 809

nCode:GlyphWorks案例教程一

nCode GlyphWorks案例一Comparing Frequency Content of Two Different Tests案例文件目标配置选择数据 Comparing Frequency Content of Two Different Tests 在本案例中,我们将比较来自两个不同测试的六个加速计通道的频率内容。将三轴加速度计放置在车辆的左前角和右前角,然后分别在两个不同的试验路面上行驶12分钟以上。 案例文件 此案例的文件(采用nCode DAC格式)位于nCode安装目录下的\demo

追月行的博客 1万+

二元树中找出和为某一值的所有路径

题目来源:http://bbs.youkuaiyun.com/topics/350118968 4.在二元树中找出和为某一值的所有路径 题目:输入一个整数和一棵二元树。 从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。 打印出和与输入整数相等的所有路径。 例如 输入整数22和如下二元树   10      / \      5 12      / \      4 7

YoungForYou的专栏 571

在 RAP 里把编号这件事做得既优雅又合规:Early Numbering 与 Late Numbering 的落地指南

本文探讨了 SAP RAP 框架中的三种主键编号策略及其适用场景。文章首先指出传统 ABAP 应用中主键处理的局限性,详细分析了早期编号(外部/内部)和延迟编号的差异,强调延迟编号在避免业务断号方面的优势。通过 Partner 业务对象案例,文章演示了延迟编号的实现方法,包括行为定义配置、保存类实现和编号分配逻辑。同时指出测试中常见的校验陷阱,并提醒生产环境应避免简单的 MAX+1 方案,建议采用原子取号机制确保并发安全。全文从业务合规性和技术实现两个维度,为 RAP 应用的编号策略选择提供了实用指导。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1842

001、专栏导论:为什么我们需要MLIR与算子中间表示

五年前,大家还在争论“TVM还是XLA”。现在回头看,TVM的Relay IR和XLA的HLO都是特定领域的IR,它们解决了各自的问题,但缺乏通用性。MLIR的出现,本质上是因为硬件异构化已经到了一个临界点——CPU、GPU、NPU、DSP、FPGA,每个硬件都有自己的指令集和内存层次,没有一个统一的IR能同时高效表达所有硬件的计算模式。MLIR的“方言+渐进式lowering”模式,恰好提供了这种灵活性。你可以为每个硬件定制一套方言,然后共享公共的lowering路径。

Jack010169的博客 488

在二元树中找出和为某一值的所有路径(树)

题目:输入一个整数和一棵二元树。 从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。 打印出和与输入整数相等的所有路径。 例如 输入整数22和如下二元树   10    / /    5 12    /  /   4     7 则打印出两条路径:10, 12和10, 5, 7。 二元树节点的数据结构定义为: struct BinaryTreeNode

yake25的专栏 2058

Spring AI Alibaba实战训练营-05模型输出质量评估

本文介绍了使用Spring AI Alibaba库评估AI模型输出质量的方案。项目通过5种评估器实现自动化评估:相关性评估、事实准确性评估、答案相关性评分、答案正确性评估和忠实度评估。开发步骤包括环境准备(Java 17、Maven、API Key获取)、创建Maven项目、配置Spring AI(通过环境变量安全设置API Key)以及实现RAG流程。重点强调了通过评估器自动检测AI输出的质量指标,帮助开发者优化AI应用性能。

program哲学 217

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

题目:输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。例如输入整数22和如下二元树                                            10

cxh342968816的专栏 515

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

上一篇: vector和dequeue的push_back比较
下一篇: 树的遍历
乔巴好萌
博客等级 码龄15年 228粉丝 47原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值