LeetCode.257.Binary Tree Paths 输出二叉树的所有路径

题目描述

257 Binary Tree Paths https://leetcode-cn.com/problems/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

解题过程

输出二叉树的所有从根到叶子的路径,可以用递归,求出左右子树的路径后再拼接上根节点即可。

public List<String> binaryTreePaths(TreeNode root) {
    List<String> result = new ArrayList<>();
    if (null == root) {
        return result;
    }
    if (null == root.left && null == root.right) {
        result.add(String.valueOf(root.val));
        return result;
    }
    binaryTreePaths(root.left).forEach(subPath -> result.add(root.val + "->" + subPath));
    binaryTreePaths(root.right).forEach(subPath -> result.add(root.val + "->" + subPath));
    return result;
}

GitHub代码

algorithms/leetcode/leetcode/_257_BinaryTreePaths.java https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_257_BinaryTreePaths.java