Given a binary tree, return all root-to-leaf paths.html
For example, given the following binary tree:node
1 / \ 2 3 \ 5
All root-to-leaf paths are:函數
["1->2->5", "1->3"]
這道題給咱們一個二叉樹,讓咱們返回全部根到葉節點的路徑,跟以前那道Path Sum II很相似,比那道稍微簡單一些,不須要計算路徑和,只須要無腦返回全部的路徑便可,那麼思路仍是用遞歸來解,博主以前就強調過,玩樹的題目,十有八九都是遞歸,而遞歸的核心就是不停的DFS到葉結點,而後在回溯回去。在遞歸函數中,當咱們遇到葉結點的時候,即沒有左右子結點,那麼此時一條完整的路徑已經造成了,咱們加上當前的葉結點後存入結果res中,而後回溯。注意這裏結果res須要reference,而out是不須要引用的,否則回溯回去還要刪除新添加的結點,很麻煩。爲了減小判斷空結點的步驟,咱們在調用遞歸函數以前都檢驗一下非空便可,代碼而很簡潔,參見以下:post
解法一:url
class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> res; if (root) helper(root, "", res); return res; } void helper(TreeNode* node, string out, vector<string>& res) { if (!node->left && !node->right) res.push_back(out + to_string(node->val)); if (node->left) helper(node->left, out + to_string(node->val) + "->", res); if (node->right) helper(node->right, out + to_string(node->val) + "->", res); } };
下面再來看一種遞歸的方法,這個方法直接在一個函數中完成遞歸調用,不須要另寫一個helper函數,核心思想和上面沒有區別,參見代碼以下:spa
解法二:code
class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { if (!root) return {}; if (!root->left && !root->right) return {to_string(root->val)}; vector<string> left = binaryTreePaths(root->left); vector<string> right = binaryTreePaths(root->right); left.insert(left.end(), right.begin(), right.end()); for (auto &a : left) { a = to_string(root->val) + "->" + a; } return left; } };
仍是遞歸寫法,從論壇中扒下來的解法,核心思路都同樣啦,寫法各有不一樣而已,參見代碼以下:htm
解法三:blog
class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { if (!root) return {}; if (!root->left && !root->right) return {to_string(root->val)}; vector<string> res; for (string str : binaryTreePaths(root->left)) { res.push_back(to_string(root->val) + "->" + str); } for (string str : binaryTreePaths(root->right)) { res.push_back(to_string(root->val) + "->" + str); } return res; } };
相似題目:遞歸
參考資料: