leetcode 257. Binary Tree Paths

原题链接: 257. Binary Tree Paths

【思路】

采用 dfs 深度遍历,用 temp 存储从根路径到当前节点的路径值。当某个节点的左右孩子都为空时,将路径的存入结果集 result 中

    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<String>();
        if (root != null) dfs(root, result, root.val + "");
        return result;
    }
    public void dfs(TreeNode root, List<String> result, String temp) {
        if (root.left == null && root.right == null) result.add(temp);
        if (root.left != null) dfs(root.left, result, temp + "->" + root.left.val);
        if (root.right != null) dfs(root.right, result, temp + "->" + root.right.val);
    }
209 / 209  test cases passed. Runtime: 2 ms  Your runtime beats 74.49% of javasubmissions.

你可能感兴趣的:(leetcode 257. Binary Tree Paths)