The problem using deep search can be done (in fact, many of the tree problems with deep search ideas can be solved), from the root node to record the path of each node, each to a leaf node to the path into the result vector can be.
/** * 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:string int2str (int src) {stringstream dst; DST << src; return Dst.str (); } void Exectraverl (treenode* root, vector<string> &result, string tmp) {if (root-left = = nullptr && root, right = = nullptr) {tmp + = "; TMP + = Int2str (root, Val); Result.push_back (TMP); Return } if (root-left! = nullptr) {string TMP1 = tmp; TMP1 + = "; TMP1 + = Int2str (root, Val); Exectraverl (Root-left, result, TMP1); } if (root-right! = nullptr) {string TMP2 = tmp; TMP2 + = "; TMP2 + = Int2str (root, Val); ExectraverL (Root-right, result, TMP2); }} vector<string> binarytreepaths (treenode* root) {string tmp; vector<string> result; if (root = = nullptr) return result; if (root, left = = nullptr && root, right = = nullptr) {tmp + = Int2str (root, Val); Result.push_back (TMP); return result; } if (root-left! = nullptr) {string tmp1; TMP1 + = Int2str (root, Val); Exectraverl (Root-left, result, TMP1); } if (root-right! = nullptr) {string tmp2; TMP2 + = Int2str (root, Val); Exectraverl (Root-right, result, TMP2); } return result; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Binary Tree Paths