本文主要是介绍[力扣题解] 257. 二叉树的所有路径,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:257. 二叉树的所有路径
思路
前序遍历
代码
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
public:vector<string> result;void travel(TreeNode* cur, vector<int>& path){int i;if(cur == NULL){return;}path.push_back(cur->val);if(cur->left == NULL && cur->right == NULL){string temp;//for(i = 0; i < path.size()-1; i++){temp.append(to_string(path[i]) + "->");}temp.append(to_string(path[i]));result.push_back(temp);}if(cur->left){travel(cur->left, path);path.pop_back();}if(cur->right){travel(cur->right, path);path.pop_back();}}vector<string> binaryTreePaths(TreeNode* root) {vector<int> path;if(root == NULL){return result;}travel(root, path);return result;}
};
这篇关于[力扣题解] 257. 二叉树的所有路径的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!