Given a binary tree, return all root-to-leaf paths.
This problem mainly uses a Java feature, string is a immutable object, can not be modified, can only regenerate
/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/ Public classSolution {/** * @paramroot The root of the binary tree *@returnAll root-to-leaf paths*/ PublicList<string>binarytreepaths (TreeNode root) {//Write Your code herelist<string> result =NewArraylist<string>(); if(Root = =NULL) returnresult; String Str=NULL; Helper (str, result, root); returnresult; } Public voidHelper (String str, list<string>result, TreeNode root) { if(Root.left = =NULL&& Root.right = =NULL){ if(str = =NULL) {str=string.valueof (Root.val); } Else{str= str + "+" +string.valueof (Root.val); } result.add (str); return; } String new_str=NULL; if(str = =NULL) {New_str=string.valueof (Root.val); } Else{new_str= str + "+" +string.valueof (Root.val); } if(Root.left! =NULL) Helper (new_str, result, root.left); if(Root.right! =NULL) Helper (new_str, result, root.right); return; }}
Lintcode-easy-binary Tree Paths