一、題目介紹
給定一個二叉樹,返回所有從根節點到葉子節點的路徑。
說明: 葉子節點是指沒有子節點的節點。
示例:
輸入:
1
/ \
2 3
\
5
輸出: ["1->2->5", "1->3"]
解釋: 所有根節點到葉子節點的路徑爲: 1->2->5, 1->3
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/binary-tree-paths
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
二、解題思路
考察二叉樹的,深度優先遍歷。利用遞歸的方法,自頂向下遍歷整個二叉樹。如果當前的節點爲葉子節點時,則保存一條路徑,通過遞歸找出所有的路徑。詳細請見代碼。
三、解題代碼
/**
* 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:
void help(TreeNode* root, vector<string>& res, string path)
{
path += to_string(root->val);
if(root->left == NULL && root->right == NULL)
{
res.push_back(path);
return;
}
if(root->left)
help(root->left, res, path + "->");
if(root->right)
help(root->right, res, path + "->");
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if(root == NULL)
return res;
help(root, res, "");
return res;
}
};