leetcode257. Binary Tree Paths

来源:互联网 发布:ubuntu des 解密 编辑:程序博客网 时间:2024/05/18 12:34

257. Binary Tree Paths

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

For example, given the following binary tree:   1 /   \2     3 \  5All root-to-leaf paths are:["1->2->5", "1->3"]

解法

dfs,直到叶子结点,生成字符串

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<String> binaryTreePaths(TreeNode root) {        List<String> answer = new ArrayList<>();        if (root == null) {            return answer;        }        searchBT(root, "", answer);        return answer;    }    public 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);        }    }}