LeetCode257 二叉树路径

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> ans = new ArrayList<>();
        if (root != null) searchBT(root, "", ans);
        return ans;
    }
    private void searchBT(TreeNode root, String path, List<String> ans){
        if (root.left == null && root.right == null) ans.add(path + root.val);
        if (root.left != null) searchBT(root.left, path + root.val +"->", ans);
        if (root.right != null) searchBT(root.right, path + root.val +"->", ans);
    }

猜你喜欢

转载自blog.csdn.net/fruit513/article/details/85373255