Topic:
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"]
Exercises
Using depth-first traversal, a binary tree-like pre-order variable traversal
Code:
public class Leetcode257_binarytreepaths {static list<string> paths=new arraylist<> ();/** * @param args */pu Blic static void Main (string[] args) {//TODO auto-generated method Stubtreenode p1=new TreeNode (1); TreeNode p2=new TreeNode (2)//treenode p3=new TreeNode (3);//treenode p4=new TreeNode (5);p 1.left=p2;//p1.right=p3;// P2.left=p4;binarytreepaths (p1);} public static list<string> binarytreepaths (TreeNode root) {if (root==null) return paths; String curpath= ""; Serachtree (Root, Curpath); return paths; } public static void Serachtree (TreeNode root,string currentpath) { currentpath+=root.val; if (root.left==null& &root.right==null) {paths.add (Currentpath); System.out.println (Currentpath); Return } currentpath+= "and"; if (root.left!=null) Serachtree (Root.left, Currentpath); if (root.right!=null) Serachtree (Root.right, Currentpath);} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
LeetCode257 binarytreepaths (print root node to left and right path of leaf node) Java