您的位置:首页 > 编程语言 > Java开发

[leetcode-257]Binary Tree Paths(java)

2015-08-24 13:18 281 查看
问题描述:

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

分析:使用递归的思想,且递归到叶节点时终止,即root.left==null && root.right == null时。

代码如下:304ms

[code]/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private void findPath(List<String> res,String tmp,TreeNode root){
        if(root==null)
            return;
        if(root.left==null && root.right==null){
            res.add(tmp+Integer.toString(root.val));
            return;
        }

        findPath(res,tmp+Integer.toString(root.val)+"->",root.left);
        findPath(res,tmp+Integer.toString(root.val)+"->",root.right);
    }
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new LinkedList<>();
        if(root==null)
            return res;

        findPath(res,"",root);
        return res;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: