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

题意:给定一个二叉树,要求返回所有根到叶节点的路径

代码

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        if(root == null) return result;
        helper(root, result, "");
        return result;
    }

    private  void helper (TreeNode root, List<String> result,  String path){
        if(root.left ==null && root.right ==null) {
           result.add(path + root.val); 
        }
        if(root.left!=null){
            helper(root.left, result, path+root.val+ "->");
        }
        if(root.right!=null){
            helper(root.right, result, path+root.val+"->");
        }   
    } 
}

results matching ""

    No results matching ""