博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Leetcode】Path Sum II
阅读量:7070 次
发布时间:2019-06-28

本文共 1292 字,大约阅读时间需要 4 分钟。

题目:

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:

Given the below binary tree and 
sum = 22
,
5             / \            4   8           /   / \          11  13  4         /  \    / \        7    2  5   1

return

[   [5,4,11,2],   [5,8,4,5]]

解题思路:用DFS算法进行搜索,搜索到叶子节点并且路径和等于设定值时,将路径存入容器。

代码:

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector
> pathSum(TreeNode *root, int sum) { vector
> Path; vector
CurrPath; build_path(Path, CurrPath, root, sum); return Path; }private: void build_path(vector
> &Path,vector
&CurrPath, TreeNode *root, int sum){ if(!root)return; CurrPath.push_back(root->val); if(!root->left&&!root->right){ if(root->val==sum)Path.push_back(CurrPath); }else{ build_path(Path,CurrPath,root->left,sum-root->val); build_path(Path,CurrPath,root->right,sum-root->val); } CurrPath.pop_back(); }};

转载于:https://www.cnblogs.com/ussam/p/3623898.html

你可能感兴趣的文章
MONyog监控系统
查看>>
后缀数组 --- HDU 3518 Boring counting
查看>>
让你的虚拟机飞起来--VMware workstaion
查看>>
Yeslab 马老师 V2V环境下vCenter Server Heartbeat v6.4实现vCenter5.0的双机备份
查看>>
ZigBee TI ZStack CC2530 1.1 总体框架
查看>>
Oracle 11g RAC ASM 错误之(1)
查看>>
LoadRunner针对Centos实施监控
查看>>
在CentOS上编译安装Nginx+实验环境搭建+测试
查看>>
RabbitMQ基本功能测试用例(Java实现)
查看>>
Android开发学习笔记:浅谈ListView
查看>>
ext-js当用blur()和focus()来控制焦点
查看>>
JAVA类型转换大全
查看>>
Powershell 比较AD和Exchange的用户登录时间
查看>>
系统出现非法操作错误解决对策
查看>>
xml文件对比或xml大字符串对比方法(蛮精简的)
查看>>
Weblogic产品模式切换与JVM切换
查看>>
论“性能需求分析”系列专题(一)之 性能需求剖析
查看>>
费波拉奇 递归
查看>>
PC 加入AD域的要求
查看>>
Enterprise Library 2.0 Hands On Lab 翻译(1):数据访问程序块(一)
查看>>