Advertisement
gelita

Binary Tree -return all root to leaf paths

Mar 17th, 2020
631
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.19 KB | None | 0 0
  1. /**
  2.  * Given a binary tree, return all root-to-leaf paths.
  3.  
  4. Note: A leaf is a node with no children.
  5.  
  6. Example:
  7.  
  8. Input:
  9.  
  10.    1
  11.  /   \
  12. 2     3
  13.  \
  14.   5
  15.  
  16. Output: ["1->2->5", "1->3"]
  17.  
  18. Explanation: All root-to-leaf paths are: 1->2->5, 1->3Definition for a binary tree node.
  19.  * public class TreeNode {
  20.  *     int val;
  21.  *     TreeNode left;
  22.  *     TreeNode right;
  23.  *     TreeNode(int x) { val = x; }
  24.  * }
  25.  */
  26. class Solution {
  27.     public List<String> binaryTreePaths(TreeNode root) {
  28.         List<String> result = new ArrayList<String>();
  29.         if(root == null){
  30.             return result;
  31.         }
  32.         //String path = Integer.toString(root.val);
  33.         traverse(result, Integer.toString(root.val), root);
  34.         return result;
  35.     }
  36.     private void traverse(List<String> result, String path, TreeNode currNode){
  37.         if(currNode.left == null && currNode.right == null){
  38.           result.add(path);
  39.           return;
  40.         }
  41.         if(currNode.left != null){
  42.           traverse(result, path + "->"+ currNode.left.val, currNode.left);
  43.         }if(currNode.right != null){
  44.           traverse(result, path + "->"+ currNode.right.val, currNode.right);
  45.         }
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement