Add to List 257. Binary Tree Paths

来源:互联网 发布:python取消注释快捷键 编辑:程序博客网 时间:2024/06/06 00:59

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”]
这道题是利用DFS算法的思路。先从root出发,然后递归左子树,再递归右子树。注意这里to_string函数用于将int型转化为string型
代码如下:

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