Skip to content

Latest commit

 

History

History
64 lines (52 loc) · 1.27 KB

257. Binary Tree Paths.md

File metadata and controls

64 lines (52 loc) · 1.27 KB

leetcode-cn Daily Challenge on September 4th, 2020.


Difficulty : Easy

Related Topics : TreeDFS


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

Solution

  • mine
    • Java
      • Runtime: 9 ms, faster than 47.07%, Memory Usage: 39.6 MB, less than 81.56% of Java online submissions
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> res = new LinkedList<>();
            if(root == null) return res;
            dfs(res, root, String.valueOf(root.val));
            return res;
        }
        
        void dfs(List<String> res, TreeNode node, String t){
            if(node.left == null && node.right == null){
                res.add(t);
                return;
            }
            if(node.left != null){
                dfs(res, node.left, t + "->" + node.left.val);
            }
            if(node.right != null){
                dfs(res, node.right, t + "->" + node.right.val);
            }
        }