Leetcode 257. 二叉树的所有路径
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例
题目解答
从题意来看,就是从二叉树的根节点开始,找出随意往不同方向一路到达不同叶子节点的所有路径。
解题方法
可想而知,这种类型的题目,个人觉得深度优先搜索(Depth-First-Search)是最适合的了。忘记了DFS是什么的同学,记得翻开课本复习一下哦,这里就不详细解说。直接上代码。
代码
/**
* 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> res;
if(!root)
return res;
DFS(root, res, to_string(root->val));
return res;
}
// 深度优先搜索
void DFS(TreeNode* root,vector<string> &res,string subPath){
// 如果当前该节点为叶子结点,则此条路径已经遍历完,将路径添加到结果中,并返回
if(root->left==NULL&&root->right==NULL){
res.push_back(subPath);
return;
}
// 左孩子非空
if(root->left){
DFS(root->left, res, subPath + "->" + to_string(root->left->val));
}
// 右孩子非空
if(root->right){
DFS(root->right, res, subPath + "->" + to_string(root->right->val));
}
}
};