【leetcode】Path Sum II

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]
]

下午做了个笔试没睡觉,晚上整个人都不好了,一点刷题的感觉都没有。
很容易想到用深度有限搜索。开始想用栈实现,结果写的乱七八槽,后来才改成用递归实现深搜。
用数组path记录从根节点到当前的路径,如果当前节点是叶节点并且找到合适的路径,就把path转成vector放入结果的二维vector中;如果当前不是叶节点,就假定它在路径上,把它放入path中,并且把sum减掉当前节点的val,供递归时候使用。
代码如下:
复制代码
 1 #include <iostream>
 2 #include <vector>
 3 #include <stack>
 4 using namespace std;
 5 
 6 struct TreeNode {
 7     int val;
 8     TreeNode *left;
 9     TreeNode *right;
10     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 };
12  
13 class Solution {
14 private:
15     int path[10000];
16     vector<vector<int> > answer;
17 public:
18     vector<vector<int> > pathSum(TreeNode *root, int sum) {
19         dfs(root,sum,0);
20         return answer;
21     }
22     void dfs(TreeNode* root,int sum,int path_index){
23         if(root == NULL)
24             return;
25         if(root->val == sum && root->left == NULL && root->right == NULL)
26         {
27             //找到一条路径
28             vector<int> temp;
29             for(int i= 0;i < path_index;i++)
30                 temp.push_back(path[i]);
31             temp.push_back(sum);//叶节点这里才进入向量
32             answer.push_back(temp);
33         }
34         else{
35             sum -= root->val;
36             path[path_index++] = root->val;
37             if(root->left != NULL)
38                 dfs(root->left,sum,path_index);
39             if(root->right != NULL)
40                 dfs(root->right,sum,path_index);
41         }
42     }
43 };
44 int main(){
45     TreeNode* treenode = new TreeNode(5);
46     TreeNode* left = new TreeNode(4);
47     treenode->left = left;
48     TreeNode* right = new TreeNode(8);
49     treenode->right = right;
50 
51     Solution s;
52     vector<vector<int> > a = s.pathSum(treenode,9);
53     for(int i = 0;i < a.size();i++){
54         std::vector<int> v = a[i];
55         for(int j = 0;j < v.size();j++)
56             cout << v[j]<<" ";
57         cout <<endl;
58     }
59 
60 }

 

复制代码
posted @   SunshineAtNoon  阅读(198)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示