257. Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> list = new ArrayList<>();
        traverseTree(list, root, "");
        return list;
    }
    
    private void traverseTree(List<String> list, TreeNode root, String str) {
        if(root == null)
            return;
        if(root.left == null && root.right == null) {
            list.add(str + root.val);
            return;
        }
        traverseTree(list, root.left, str + root.val + "->");
        traverseTree(list, root.right, str + root.val + "->");
    }
}

有点僵硬,是普通的dfs

posted @ 2019-11-05 14:05  Schwifty  阅读(105)  评论(0)    收藏  举报