ITeye博客

Binary Tree Paths

KickCode · 2016-02-25 01:40 · Leetcode · 编程语言 · Markdown

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:

给定一个二叉树,输出从根到叶子节点的路径。用递归来完成,代码如下:


/**
 * 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> list = new ArrayList<String>();
        if(root == null) return list;
        getPath(root, String.valueOf(root.val), list);
        return list;
    }
    public void getPath(TreeNode root, String s, List<String> list) {
        if(root.left == null && root.right == null)
            list.add(s);
        if(root.left != null)
            getPath(root.left, s + "->" + root.left.val, list);
        if(root.right != null)
            getPath(root.right, s + "->" + root.right.val, list);
    }
    
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。