IncredibleThings

导航

LeetCode-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

思路:看到题目就知道要用DFS做,注意结束递归的条件

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        dfsHelper(root, "", list);
        return list;
    }
    
    public void dfsHelper (TreeNode node, String str, List<String> list) {
        if (node == null) {
            return;
        }
        if (node.left == null && node.right == null) {
            list.add(str + node.val);
            return;
        }
        String updatedStr = str + node.val + "->";
        dfsHelper(node.left, updatedStr, list);
        dfsHelper(node.right, updatedStr, list);
        
    }
}

 

posted on 2019-10-15 13:06  IncredibleThings  阅读(120)  评论(0编辑  收藏  举报