您的位置 首页 JAVA(2017)

257. Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   \
2     3
 \
  5

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> res= new ArrayList<String>();
        if(root != null){
            DFS(root,"",res);
        }
        return res;
    }
    public void DFS(TreeNode root, String val, List<String> res){
        if(root.left == null && root.right == null){
            res.add(val+root.val);
        }
        if(root.left != null){
            DFS(root.left, val+ root.val+"->",res);
        }
        if(root.right != null){
            DFS(root.right, val+ root.val+"->",res);
        }
    }
}
看完了?留个评分呗?
[0人评了分,平均: 0/5]

本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:

原文来源:《257. Binary Tree Paths》

发表评论

邮箱地址不会被公开。

返回顶部