首页 > 其他 > 详细

[LC] 257. Binary Tree Paths

时间:2019-12-07 14:39:55      阅读:71      评论:0      收藏:0      [点我收藏+]

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

/**
 * 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> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        helper(root, res, "");
        return res;
    }
    
    private void helper(TreeNode root, List<String> res, String str) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            res.add(str + root.val);
            return;
        }
        String newStr = str + root.val + "->";
        helper(root.left, res, newStr);
        helper(root.right, res, newStr);
    }
}

 

[LC] 257. Binary Tree Paths

原文:https://www.cnblogs.com/xuanlu/p/12001283.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!