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 is:
["1->2->5", "1->3"]
Credits:
Special thanks to @jianchao. Li.fighter for adding the problem and creating all test cases.
Subscribe to see which companies asked this question
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 */Ten Public classSolution { Onelist<string> ans =NewArraylist<string>(); A PublicList<string>binarytreepaths (TreeNode root) { - if(Root = =NULL)returnans; -String tmp = "" +Root.val; the DFS (ans,root,tmp); - returnans; - } - + Public voidDFS (list<string>ans, TreeNode node, String tmp) { - if(Node.left = =NULL&& Node.right = =NULL){ + Ans.add (TMP); A return; at } - if(Node.left! =NULL) DFS (ans,node.left,tmp+ "+" +node.left.val); - if(Node.right! =NULL) DFS (ans,node.right,tmp+ "+" +node.right.val); - } -}
Use recursion.
257. Binary Tree Paths Java Solutions