算法分析与设计week19--257. Binary Tree Paths

257. Binary Tree Paths

Description

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

Example

For example, given the following binary tree:

1
/ \
2 3
\
5
All root-to-leaf paths are:

[“1->2->5”, “1->3”]

Analysis

思路:用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> result;
        if(root) dfs(root, "", result);
        return result;
    }

    void dfs(TreeNode *root, string out, vector<string> &result) {
        out += to_string(root->val);
        if(root->left == NULL && root->right == NULL) result.push_back(out);
        else {
            if(root->left) dfs(root->left, out + "->", result);
            if(root->right) dfs(root->right, out + "->", result);
        }
    }
};

下面再来看一种递归的方法,这个方法直接在一个函数中完成递归调用,不需要另写一个dfs函数,核心思想和上面没有区别

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        if (!root) return {};
        if (!root->left && !root->right) return {to_string(root->val)};
        vector<string> left = binaryTreePaths(root->left);
        vector<string> right = binaryTreePaths(root->right);
        left.insert(left.end(), right.begin(), right.end());
        for (auto &a : left) {
            a = to_string(root->val) + "->" + a;
        }
        return left;
    }
};

你可能感兴趣的:(算法设计与分析作业)