# Leetcode#257. Binary Tree Paths（二叉树的所有路径）

2018-01-30 10:44:49来源:网络收集作者:咖啡不加糖人点击

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++语言
/**
* 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:
vectorres;
void getPaths(TreeNode* root, string now_path)
{
if(root->left==NULL && root->right==NULL)//左右子树都为空，一条路径查找结束
{
res.push_back(now_path);
}
if(root->left!=NULL)//左子树不为空，先添加当前元素，再查找
{
getPaths(root->left, now_path + "->" + to_string(root->left->val));
}
if(root->right!=NULL)
{
getPaths(root->right, now_path + "->" + to_string(root->right->val));
}
}
vector binaryTreePaths(TreeNode* root) {
if(root==NULL)
return res;
getPaths(root, to_string(root->val));
return res;
}
};
Python语言

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
#self.val = x
#self.left = None
#self.right = None
class Solution(object):
def getPaths(self,root, now_path, res):
if root.left==None and root.right==None:
res.append(now_path)
if root.left!=None:
self.getPaths(root.left, now_path + "->" + str(root.left.val), res)
if root.right!=None:
self.getPaths(root.right, now_path + "->" + str(root.right.val), res)
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
res = []
if root == None:
return res
self.getPaths(root, str(root.val),res)
return res
Python语言

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
#self.val = x
#self.left = None
#self.right = None
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
res = []
def getPaths(root, now_path):
if root.left==None and root.right==None:
res.append(now_path)
if root.left!=None:
getPaths(root.left, now_path + "->" + str(root.left.val))
if root.right!=None:
getPaths(root.right, now_path + "->" + str(root.right.val))
if root == None:
return res
getPaths(root, str(root.val))
return res