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"]
The use of deep traversal, and recursive method. You can also use stacks, but the recursive approach is simple, but takes a long time
/** * 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> svec;string Str;if (root = NULL) return Svec;dfs (Root, str, SVEC); return Svec;} void Dfs (TreeNode *root, String str, vector<string> &svec) { if (root==nullptr) return;if (root-> left = = Null&&root->right = NULL) { str+=to_string (root->val); Svec.push_back (str);//If you traverse to a leaf node, The path is placed in the container to return;} DFS (Root->left, str+to_string (root->val) + "-", svec);//traversal of the left subtree Dfs (root->right, str+to_string (root- >val) + "--", svec);//Traverse Right sub-tree} };
Leetcode Binary Tree Paths