题目描述:
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"]
看到树相关的题目,第一反应就是递归,下面是我的代码:
vectorbinaryTreePaths(TreeNode* root) { vector res; if (root != NULL) { char buf[20]; sprintf(buf, "%d", root->val); string rootPath = buf; if (root->left == NULL && root->right == NULL) { res.push_back(rootPath); } else { if (root->left) { vector leftPath; leftPath = binaryTreePaths(root->left); for (vector ::iterator it = leftPath.begin(); it != leftPath.end(); ++it) { res.push_back(rootPath + "->" + *it); } } if (root->right) { vector rightPath; rightPath = binaryTreePaths(root->right); for (vector ::iterator it = rightPath.begin(); it != rightPath.end(); ++it) { res.push_back(rootPath + "->" + *it); } } } } return res;}
想要简洁一点的,可以参考