题目:
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: void RootPath(vector<string>& resultVec, TreeNode *root, string s) { if (root->left == NULL && root->right == NULL) { resultVec.push_back(s); return; } if (root->left) { RootPath(resultVec, root->left, s + "->" + to_string(root->left->val)); } if (root->right) { RootPath(resultVec, root->right, s + "->" + to_string(root->right->val)); } } vector<string> binaryTreePaths(TreeNode* root) { vector<string> result; if (root == NULL) return result; RootPath(result, root, to_string(root->val)); return result; } };
时间: 2024-10-18 08:15:09