257. Binary Tree Paths*

257. Binary Tree Paths*

https://leetcode.com/problems/binary-tree-paths/

题目描述

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

C++ 实现 1

可以从递归和 dfs+backtracing 两个角度来考虑这个问题. 先从递归角度来看.

/**
 * 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)
            return vector<string>();

        vector<string> res;
        if (!root->left && !root->right)
            res.push_back(std::to_string(root->val));

        auto vec1 = binaryTreePaths(root->left);
        auto vec2 = binaryTreePaths(root->right);
        if (!vec1.empty()) {
            for (const auto &path : vec1)
                res.push_back(to_string(root->val) + "->" + path);
        }
        if (!vec2.empty()) {
            for (const auto &path : vec2)
                res.push_back(to_string(root->val) + "->" + path);
        }
        return res;
    }
};

C++ 实现 2

再从 DFS+Backtracing 的角度来看.

/**
 * 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 {
private:
    void dfs(TreeNode *root, vector<int> &cur, vector<vector<int>> &res) {
        if (!root) return;
        cur.push_back(root->val);
        if (!root->left && !root->right) {
            res.push_back(cur);
            return;
        }
        if (root->left) {
            dfs(root->left, cur, res);
            cur.pop_back();
        }
        if (root->right) {
            dfs(root->right, cur, res);
            cur.pop_back();
        }
    }
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        if (!root) return {};
        vector<int> cur;
        vector<vector<int>> res;
        dfs(root, cur, res);
        vector<string> paths;
        for (auto &v : res) {
            string path;
            path += std::to_string(v[0]);
            for (int i = 1; i < v.size(); ++i)
                path += "->" + std::to_string(v[i]);
            paths.push_back(path);
        }
        return paths;
    }
};
发布了327 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/104510931