LeetCode[257] Binary Tree Paths

来源:互联网 发布:linux ftp 防火墙设置 编辑:程序博客网 时间:2024/06/11 17:37

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"]


每遍历一个节点就把节点的val值添加到string中,每碰到一个叶子节点就把当前的string加入到vector<string>中

/** * 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> result;if (root == NULL)return result;Solution::PathString(result, root, to_string(root->val));return result;}void PathString(vector<string>& result, TreeNode* pNode, string path){if (pNode->left == NULL && pNode->right == NULL)result.push_back(path);if (pNode->left)PathString(result, pNode->left, path + "->" + to_string(pNode->left->val));if (pNode->right)PathString(result, pNode->right, path + "->" + to_string(pNode->right->val));}};

0 0
原创粉丝点击