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 is:
["1->2->5", "1->3"]
Analysis: Depth-First search
/** Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: Vector<string>result; Vector<string> binarytreepaths (treenode*root) { if(Root = NULL)returnresult; strings; Binarytreepaths (Root, S+to_string (root->val)); returnresult; } voidBinarytreepaths (treenode* root,stringpath) { if(Root->left = = NULL && Root->right = =NULL) {result.push_back (path); return; } Else { if(Root->left! =NULL) binarytreepaths (Root->left, path+" -"+to_string (root->left->val)); if(Root->right! =NULL) binarytreepaths (Root->right, path+" -"+to_string (root->right->val)); } }};
[Leetcode] Binary Tree Paths