LeetCode 257——二叉树的所有路径(递归)

一、题目介绍

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

输入:

   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;        
    }
};

四、解题结果

发布了139 篇原创文章 · 获赞 122 · 访问量 4716

猜你喜欢

转载自blog.csdn.net/qq_39661206/article/details/103909605
今日推荐