这道题的做法就是把模式记下来。源函数是传入一个二叉树(treeNode*),但是我们应该自己再实现一个函数search用于传递结点、vector<string>的引用和string path,这样可以递归的去调用search,当然,在search中一开始就有结束条件,遇到结束条件会return。随着不断地递归,只要不满足结束条件--------root的left和right都为NULL,该递归就会不断地增长path,并在结束时将这条path push_back()进vector中。
下面是C++代码:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
vector<string> binaryTreePaths(TreeNode* root) {
// Write your code here
vector<string> vecStr;
if (root == NULL){
return vecStr;
}
stringstream ss;
ss<<root->val;
string temp = ss.str();
search(root,temp,vecStr);
return vecStr;
}
void search(TreeNode* root, string path, vector<string>& vecStr){
//if (root == NULL){
// return;
//}
if (root->right == NULL && root->left == NULL){
vecStr.push_back(path);
return;
}
string path1 = path;
if (root->left != NULL) {
stringstream ss;
ss<<root->left->val;
string temp = ss.str();
//string temp(root->left->val);
path = path + "->" + temp;
search(root->left, path,vecStr);
}
if (root->right != NULL) {
stringstream ss;
ss<<root->right->val;
string temp = ss.str();
path = path1 + "->" + temp;
search(root->right, path, vecStr);
}
}
}; //43ms
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
# @param {TreeNode} root the root of the binary tree
# @return {List[str]} all root-to-leaf paths
def binaryTreePaths(self, root):
# Write your code here
li = []
if root == None:
return li
path = str(root.val)
self.search(root,path,li)
return li
def search(self, root, path, li):
if root.left==None and root.right==None:
li.append(path)
return
pathtemp = path
if root.left != None:
path += '->' + str(root.left.val)
self.search(root.left, path, li)
if root.right != None:
path = pathtemp + '->' + str(root.right.val)
self.search(root.right, path, li) //460ms