首页 > 其他 > 详细

LeetCode-Binary Tree Paths

时间:2019-10-15 14:04:32      阅读:59      评论: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

思路:看到题目就知道要用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);
        
    }
}

 

LeetCode-Binary Tree Paths

原文:https://www.cnblogs.com/incrediblechangshuo/p/11677065.html

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