Leetcode 257: Binary Tree Paths

问题描述

在这里插入图片描述

java实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
     //way1
    //递归  分治的思想
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> paths=new ArrayList<String>();
        
        if(root==null)
            return paths;
        //root为一个叶子节点
        if(root.left==null && root.right==null){
            paths.add(""+root.val);
            return paths;
        }
        
        //分
        List<String> leftPaths=binaryTreePaths(root.left);
        List<String> rightPaths=binaryTreePaths(root.right);
        //和
        for (String path:leftPaths)
            paths.add(root.val+"->"+path);
        for (String path:rightPaths)
            paths.add(root.val+"->"+path);
        return paths;
        
    }
}
发布了172 篇原创文章 · 获赞 22 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44135282/article/details/103828159