257. Binary Tree Paths

    xiaoxiao2025-04-17  7

    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"]

    /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> path=new ArrayList<>(); if(root!=null)binaryTP(root,"",path); return path; } public void binaryTP(TreeNode root,String paths,List<String> path) { if(root.right==null&&root.left==null) path.add(paths+root.val); if(root.left!=null){ binaryTP(root.left,paths+root.val+"->",path); } if(root.right!=null){ binaryTP(root.right,paths+root.val+"->",path); } } }

    转载请注明原文地址: https://ju.6miu.com/read-1298152.html
    最新回复(0)