15算法课程 257. Binary Tree Paths

来源:互联网 发布:djvu转pdf软件 编辑:程序博客网 时间:2024/05/22 00:16



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"]


solution:

写两个binaryTreePaths函数,第一个使用递归方法构造题目要求的字符串,这个函数需要合理选择参数;第二个函数用来返回结果


code:

/** * 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 binaryTreePaths(TreeNode* root, string s, vector<string> &result) {        if (!root->left && !root->right) {            result.push_back(s);            return;        }        if (root->left) binaryTreePaths(root->left, s + "->" + to_string(root->left->val), result);        if (root->right) binaryTreePaths(root->right, s + "->" + to_string(root->right->val), result);    }    vector<string> binaryTreePaths(TreeNode* root) {        vector<string> vec;        if (root == NULL) return vec;        binaryTreePaths(root, to_string(root->val), vec);        return vec;    }};
原创粉丝点击