Binary Tree Paths

题目来源
Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

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

我想的是深度遍历一遍。
代码如下:

/**
 * 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 binaryTreePaths(TreeNode* root) {
        vector paths;
        string path;
        dfs(root, paths, path);
        return paths;
    }
    
    void dfs(TreeNode *node, vector &paths, string path)
    {
        if (!node)
            return;
        if (path.empty())
            path += to_string(node->val);
        else
            path += "->" + to_string(node->val);
        if (!node->left && !node->right) {
            paths.push_back(path);
            return;
        }
        dfs(node->left, paths, path);
        dfs(node->right, paths, path);
    }
};

改进了一下,少了一些判断。

/**
 * 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 binaryTreePaths(TreeNode* root) {
        vector paths;
        string path;
        if (!root)
            return paths;
        dfs(root, paths, to_string(root->val));
        return paths;
    }
    
    void dfs(TreeNode *node, vector &paths, string path)
    {
        if (!node->left && !node->right) {
            paths.push_back(path);
            return;
        }
        if (node->left)
            dfs(node->left, paths, path + "->" + to_string(node->left->val));
        if (node->right)
            dfs(node->right, paths, path + "->" + to_string(node->right->val));
    }
};

你可能感兴趣的:(Binary Tree Paths)