LeetCode OJ 257. Binary Tree Paths
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"]
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
这个题目的难点在与分裂路径,我们在遍历到一个节点的时候需要把到达它的路径告诉它,如果这个节点是叶子节点,则把它加入路径然后添加到路径集合中。如果它不是叶子节点,则把它添加到路径中,并且继续遍历它的子节点。代码如下:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<String> list = new ArrayList(); 12 13 public List<String> binaryTreePaths(TreeNode root) { 14 if(root == null) return list; 15 String s = ""; 16 path(root, s); 17 return list; 18 } 19 20 public void path(TreeNode root, String p){ 21 String s = new String(p); 22 if(root.left==null && root.right==null){//如果是叶子节点 23 s = s + root.val; 24 list.add(s); 25 } 26 else s = s + root.val + "->"; 27 if(root.left!=null) //如果左子树非空 28 path(root.left, s); 29 if(root.right!=null) //如果右子树非空 30 path(root.right, s); 31 } 32 }