博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode: Path Sum II 迭代法
阅读量:6980 次
发布时间:2019-06-27

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

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

通过一个p指针,遍历 二叉树,并将每次的值 保存在 sum2 中 。

遇到右节点,将右节点+depth 保存在 temp中,当再次使用 该节点时,根据depth 将sum2中的长度削减成 depth-1

 

/** * Definition for a binary tree node. * 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
> re; if(root==NULL) return re; TreeNode *p=root; int depth=1; vector
> temp; // 保存右节点+depth vector
sum2; // 保存一条路径的所有点值 pair
t=make_pair(root,depth); // temp.push_back(t); while(!temp.empty()||p!=NULL){ sum2.push_back(p->val); if(p->left!=NULL){ if(p->right!=NULL){ temp.push_back(make_pair(p->right,depth+1)); } p=p->left; depth++; } else{ if(p->right==NULL){ int result=0; for(int i=0;i
right; depth++; } } } return re; }};

 

转载于:https://www.cnblogs.com/NeilZhang/p/5499438.html

你可能感兴趣的文章
ARP(Accounting Resource Planning)项目感想
查看>>
Linux系统基础-管理之用户、权限管理
查看>>
wordpress jquery加载如何实现?
查看>>
Lucene.net: the main concepts
查看>>
mongodb学习笔记6--杂项与补充
查看>>
solrcloud Read and Write Side Fault Tolerance
查看>>
ADF12C 在线预览PDF文件 afinlineFrame
查看>>
iOS Block实现探究
查看>>
nginx虚拟目录配置
查看>>
Python:UTF-8编码转换成GBK编码
查看>>
各种 django 静态文件的配置总结【待续】
查看>>
渐进符号
查看>>
Centos 64位 Install certificate on apache 即走https协议
查看>>
JQuery遮罩层
查看>>
认识HTML5的WebSocket 认识HTML5的WebSocket
查看>>
SQL with NUll处理,Join系列,between,in对比exists以及少量题目
查看>>
更换博客地址
查看>>
Ring Tone Manager on Windows Mobile
查看>>
openresty 前端开发入门五之Mysql篇
查看>>
MySQL编码引发的两个问题
查看>>