leetcode--Binary Tree Paths

来源:互联网 发布:mysql高并发优化方案 编辑:程序博客网 时间:2024/04/29 21:20

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

解:
用递归解最方便,但写法上稍有些不同
一.

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def binaryTreePaths(self, root):        """        :type root: TreeNode        :rtype: List[str]        """        return self.stringPath(root)    def stringPath(self,root):        li=[]        if root is None:            return []        elif not(root.left or root.right):            return [str(root.val)]        else:            left=self.stringPath(root.left)            right=self.stringPath(root.right)            for sl in range(len(left)):                left[sl]=str(root.val)+'->'+left[sl]            for rl in range(len(right)):                right[rl]=str(root.val)+'->'+right[rl]            return left+right

二.

public List<String> binaryTreePaths(TreeNode root) {    List<String> answer = new ArrayList<String>();    if (root != null) searchBT(root, "", answer);    return answer;}//这里传递一个String path参数表示在这之前的路径信息private void searchBT(TreeNode root, String path, List<String> answer) {    if (root.left == null && root.right == null) answer.add(path + root.val);    if (root.left != null) searchBT(root.left, path + root.val + "->", answer);    if (root.right != null) searchBT(root.right, path + root.val + "->", answer);}
0 0