-
Notifications
You must be signed in to change notification settings - Fork 0
257. Binary Tree Paths
Jacky Zhang edited this page Aug 17, 2016
·
1 revision
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"]
Tree类题目。
解题思路为DFS。
/**
* 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>();
helper(root, res, "");
return res;
}
private void helper(TreeNode node, List<String> res, String path) {
if(node == null) return;
if(node.left == null && node.right == null) {
path += node.val;
res.add(path);
return;
}
path = path + node.val + "->";
helper(node.left, res, path);
helper(node.right, res, path);
}
}