257. Binary Tree Paths

来源:互联网 发布:淘宝助理发货地 编辑:程序博客网 时间:2024/06/16 20:41

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


c++版:

void binaryTreePaths(vector<string>& result, TreeNode* root, string t) {    if(!root->left && !root->right) {        result.push_back(t);        return;    }    if(root->left) binaryTreePaths(result, root->left, t + "->" + to_string(root->left->val));    if(root->right) binaryTreePaths(result, root->right, t + "->" + to_string(root->right->val));}vector<string> binaryTreePaths(TreeNode* root) {    vector<string> result;    if(!root) return result;        binaryTreePaths(result, root, to_string(root->val));    return result;}


python版:

# Definition for a binary tree node.# class TreeNode:#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution:    def binaryTreePaths(self, root):        """        :type root: TreeNode        :rtype: List[str]        """        if not root:            return []        return [str(root.val)+'->'+path                for kid in (root.left,root.right) if kid                for path in self.binaryTreePaths(kid)] or [str(root.val)]