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"]
解题思路:
依然recursion! 用DFS。 关键点:让路径string 伴随着遍历树的点,点到哪里,路径值跟到哪里。
Java code:
/** * 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> result = new ArrayList<String>(); if(root == null) { return result; } String path = root.val + ""; getPath(root, result, path); return result; } void getPath(TreeNode root, List<String> result, String path) { if(root.left == null && root.right == null) { result.add(path); } if(root.left != null) { getPath(root.left, result, path+"->"+root.left.val+""); } if(root.right != null) { getPath(root.right, result, path+"->"+root.right.val+""); } } }
Reference:
1. http://www.hihuyue.com/hihuyue/codepractise/leetcode/leetcode174-binary-tree-paths