当前位置

网站首页> 程序设计 > 开源项目 > 程序开发 > 浏览文章

[LintCode] Binary Tree Paths - Road to Glory

作者:小梦 来源: 网络 时间: 2024-02-09 阅读:

Problem

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

Example

Given the following binary tree:

   1 /   \2     3 \  5

All root-to-leaf paths are:

[  "1->2->5",  "1->3"]

Solution

public class Solution {    public List<String> binaryTreePaths(TreeNode root) {        // Write your code here        List<String> res = new ArrayList<String>();        if (root == null) {return res;        }        findpaths(root, res, root.val + "");//这里+""巧妙地调用了String        return res;    }    public void findpaths(TreeNode root, List<String> res, String cur) {   if (root.left != null) {           findpaths(root.left, res, cur + "->" + root.left.val);        }        if (root.right != null) {           findpaths(root.right, res, cur + "->" + root.right.val);        }        if (root.left == null && root.right == null) {           res.add(cur);           return;        }    }}

热点阅读

网友最爱