給定一個二叉樹,返回所有從根節點到葉子節點的路徑。
說明:?葉子節點是指沒有子節點的節點。
示例:
輸入:
? ?1
?/ ? \
2 ? ? 3
?\
? 5
輸出: ["1->2->5", "1->3"]
解釋: 所有根節點到葉子節點的路徑為: 1->2->5, 1->3
思路:全局list答案記錄即可。
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
class Solution {LinkedList<String> paths = new LinkedList();public void helper(TreeNode root, String path) {if (root == null)return;path += Integer.toString(root.val);if (root.left == null && root.right == null){// 當前節點是葉子節點,找到一個答案paths.add(path);}else {path += "->";helper(root.left, path);helper(root.right, path);}}public List<String> binaryTreePaths(TreeNode root) {helper(root, "");return paths;}
}
?