Java [Leetcode 257]Binary Tree Paths

1319 ワード

タイトルの説明:
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> res = new ArrayList<String>();
        if(root != null)
        	searchTree(res, root, "");
        return res;
    }
	 
	public void searchTree(List<String> res, TreeNode root, String connection){
		if(root.left == null && root.right == null)
			res.add(connection + root.val);
		if(root.left != null)
			searchTree(res, root.left, connection + root.val + "->");
		if(root.right != null)
			searchTree(res, root.right, connection + root.val + "->");
	}
}