Lettcode_257_Binary Tree Paths

Source: Internet
Author: User

Lettcode_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]

 

Ideas:

(1) give a tree and find all the paths from the root to the leaf node.

(2) The question is actually the depth-first traversal of the tree. This article uses recursive methods to solve the problem. Starting from the root node, if the left subtree is not empty, the left subtree is traversed. If the left subtree is not empty, traverse the left child. Otherwise, traverse the right child ..... until the last leaf node is traversed. If you use a non-recursive algorithm, you need to set a stack to store the Left and Right Subtrees. This is also a good implementation.

(3) For details, see the code below. I hope this article will help you.

 

 

package leetcode;import java.util.ArrayList;import java.util.List;import leetcode.utils.TreeNode;public class Binary_Tree_Paths {public static void main(String[] args) {TreeNode r = new TreeNode(1);TreeNode r1 = new TreeNode(2);TreeNode r2 = new TreeNode(3);TreeNode r3 = new TreeNode(5);r.left = r1;r.right = r2;r1.right = r3;binaryTreePaths(r);}public static List
 
   binaryTreePaths(TreeNode root) {List
  
    result = new ArrayList
   
    ();if (root != null) {getpath(root, String.valueOf(root.val), result);}return result;}private static void getpath(TreeNode root, String valueOf,List
    
      result) {if (root.left == null && root.right == null)result.add(valueOf);if (root.left != null) {getpath(root.left, valueOf + -> + root.left.val, result);}if (root.right != null) {getpath(root.right, valueOf + -> + root.right.val, result);}}}
    
   
  
 


 

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.