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"] 采用的是深度遍历,而且是用递归的方法。也可以用栈,不过递归的方法简单,但是耗时长
/** * 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); //如果遍历到叶子节点,则将这个路径放到容器中去 return; } dfs(root->left, str+to_string(root->val)+"->", svec);//遍历左子树 dfs(root->right, str+to_string(root->val)+"->", svec);//遍历右子树 } };
时间: 2024-10-13 16:27:24