Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / / 2 3 / 5 All root-to-leaf paths are:
[“1->2->5”, “1->3”]
深搜,簡(jiǎn)單的遞歸: 和之前不一樣的是,搜索到葉子結(jié)點(diǎn)就需要返回,同時(shí)要在葉子結(jié)點(diǎn)處將本次的路徑保存進(jìn)結(jié)果的vector。 之所以又寫了一個(gè)dfs是為了可以在遞歸的過(guò)程中同時(shí)記錄下路徑。
/** * 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<string> binaryTreePaths(TreeNode* root) { vector<string> rlt; dfs(root, "", rlt); return rlt; } void dfs(TreeNode* root, string sPRe, vector<string> &res) { if (!root) return; spre += to_string(root->val); if (!root->left && !root->right) { res.push_back(spre); return ; } spre += "->"; if(root->left && root->right) { dfs(root->left,spre,res); dfs(root->right,spre,res); } else if(!root->left) { dfs(root->right,spre,res); } else if(!root->right) { dfs(root->left,spre,res); } return ; }};新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注