Binary Tree Paths ---LeetCode

来源:互联网 发布:bugs软件 编辑:程序博客网 时间:2024/06/06 16:54

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<String> result = new ArrayList<>();    public List<String> 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);    }}
0 0
原创粉丝点击