博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LintCode 二叉树的路径和
阅读量:4205 次
发布时间:2019-05-26

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

样例

给定一个二叉树,和 目标值 = 5:

1    / \   2   4  / \ 2   3

返回:

[  [1, 2, 2],  [1, 4]]

解法:DFS,注意路径和的概念,要到叶子节点

AC代码:

class Solution {public:    /*     * @param root: the root of binary tree     * @param target: An integer     * @return: all valid paths     */    vector
> binaryTreePathSum(TreeNode * root, int target) { // write your code here vector
> res; if(!root){ return res; } vector
a; TreePathSum(root, target, 0, a, res); return res; } void TreePathSum(TreeNode * root, int target,int now, vector
& a, vector
> &res) { // write your code here now += root->val; a.push_back(root->val); if(now == target){ if(!root->right && !root->left ) res.push_back(a); } if(root->left){ TreePathSum(root->left, target, now, a, res); a.pop_back(); } if(root->right){ TreePathSum(root->right, target, now, a, res); a.pop_back(); } return ; }};

转载地址:http://axoli.baihongyu.com/

你可能感兴趣的文章
DRM in Android
查看>>
ARC MRC 变换
查看>>
Swift cell的自适应高度
查看>>
【linux】.fuse_hiddenXXXX 文件是如何生成的?
查看>>
【LKM】整合多个LKM为1个
查看>>
【Kernel】内核热补丁技术揭秘
查看>>
【Error】/usr/bin/env: ‘python’: No such file or directory
查看>>
手工挂载VMware共享目录
查看>>
【Kernel】pid 与 tgid
查看>>
【Error】make LKM时 找不到符号
查看>>
【转载】【C语言】浅析C语言之uint8_t / uint16_t / uint32_t /uint64_t
查看>>
【转载】yum update 自动忽略内核更新
查看>>
【maven】打包jar上传到服务器运行
查看>>
关闭centos wayland
查看>>
【Error】chsh: PAM: Authentication failure
查看>>
【Error】zsh历史记录丢失
查看>>
解析漏洞总结
查看>>
有趣的二进制 读书笔记
查看>>
【Windows C++】调用powershell上传指定目录下所有文件
查看>>
kotlin-android-extensions 插件无效问题
查看>>