Binary Tree Paths ---LeetCode

https://leetcode.com/problems/binary-tree-paths/

解题思路:

这道题需要求返回所有从根节点到叶子节点的路径,用递归实现。求路径的题目思想都大差不差,注意细节就好。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {

    List result = new ArrayList<>();

    public List binaryTreePaths(TreeNode root) {
        if (root == null) return result;
        helper(root, String.valueOf(root.val));
        return result;
    }
    public void helper(TreeNode root, String path) {
        if (root.left == null && root.right == null)
            result.add(path);
        if (root.left != null)
            helper(root.left, path + "->" + root.left.val);
        if (root.right != null)
            helper(root.right, path + "->" + root.right.val);
    }
}

你可能感兴趣的:(Leetcode,递归,Leetcode,java,path,算法)