LeetCode257 binarytreepaths (print root node to left and right path of leaf node) Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.