LeetCode Path Sum II (DFS)

來源:互聯網
上載者:User

標籤:

 

題意:

  給一棵二叉樹,每個葉子到根的路徑之和為sum的,將所有可能的路徑裝進vector返回。

 

思路:

  節點的值可能為負的。這樣子就必須到了分葉節點才能判斷,而不能中途進行剪枝。

 

 

 1 /** 2  * Definition for a binary tree node. 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 11 12 class Solution {13 public:14     vector<vector<int> > pathSum(TreeNode* root, int sum) {15         if(root==NULL)  return ans;16         DFS(root,0,sum,tmp);17         return ans;18     }19     void DFS(TreeNode* t,int n,const int& sum,vector<int>& num)20     {21         num.push_back(t->val);22         n+=t->val;23 24         if(t->left==NULL&&t->right==NULL)25         {26             if(n==sum)  ans.push_back(num);27         }28         else29         {30             if(t->left)     DFS(t->left,n,sum,num);31             if(t->right)    DFS(t->right,n,sum,num);32         }33         num.pop_back();34     }35 private:36     vector<vector<int>> ans;37     vector<int> tmp;38 };
AC代碼

 

LeetCode Path Sum II (DFS)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.