【LeetCode-树】二叉树的所有路径

题目描述

给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:

输入:

   1
 /   
2     3
 
  5

输出: ["1->2->5", "1->3"]

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

思路

使用 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) {
        if(root==nullptr) return {};
        
        vector<string> ans;
        string curPath = "";
        dfs(root, curPath, ans);
        return ans;
    }

    void dfs(TreeNode* root, string curPath, vector<string>& ans){
        if(root==nullptr) return;
        if(root->left==nullptr && root->right==nullptr){  // 叶子节点不加 "->"
            curPath += to_string(root->val);
            ans.push_back(curPath);
            return;
        }

        dfs(root->left, curPath + to_string(root->val) + "->", ans);
        dfs(root->right, curPath + to_string(root->val) + "->", ans);
    }
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(h)
    h 为树高。
原文地址:https://www.cnblogs.com/flix/p/12885529.html