Skip to main content

Binary Tree Paths



Source:LeetCode

Solution: We do a preorder traversal add each node in the string followed by an arrow "->" if the current node is a leaf node (have no right or left child) then we add the string to the list, otherwise, we add an arrow and make a recursive call in a preorder fashion. The previous string is stored in stack and we can use it later when the call is returned to add another possible routes from root to the leaf nodes. 


Complexity Analysis

  • Time complexity : O(n). n nodes need to be traversed (n represents the number of nodes in a given tree).
  •  
Solution:


 public List<String> binaryTreePaths(TreeNode root) {
        
        ArrayList<String> path = new ArrayList();
        binaryPath(root,"",path);
        return path;         
    }
    public static void binaryPath(TreeNode root,String s,List<String> path){
     
          if(root == null)
                return;
        
           s+=""+root.val;                 
           if(root.left == null && root.right == null) //add string to list if leaf node
               path.add(s);
        
           s+="->"; //add arrow if it's NOT a leaf node
           binaryPath(root.left,s,path); 
           binaryPath(root.right,s,path);    
         }


Solution using StringBuilder:  String in Java is immutable, so every time append the number or arrow it will create a new string object. Thus, StringBuilder will be ideal in this problem as it's mutable.


 public List<String> binaryTreePaths(TreeNode root) {
        
        ArrayList<String> path = new ArrayList();
        StringBuilder sb = new StringBuilder("");
        binaryPath(root,sb,path);
        return path;         
    }
    public static void binaryPath(TreeNode root,StringBuilder sb,List<String> path){
        
        if(root!= null){
             int len = sb.length();
             sb.append(""+root.val);
            
            if(root.left == null && root.right == null)
                path.add(sb.toString());    //add string to list
            
             sb.append("->");
             binaryPath(root.left,sb,path); //preorder traversal
             binaryPath(root.right,sb,path);    
             sb.setLength(len);        //set length back accordingly
        }
        
    }

Comments

Popular posts from this blog

RLE Encoding and Decoding in C++

Given an input string, write a regular recursive function that returns the decoded (uncompresseed form) Run Length Encoded   (is a simple form of data compression where repeated character are replaced by count followed by the character repeated) string for the input string. Below are some examples: decode("*") =>* decode("3+") =>+++ decode("11*") =>*********** decode("101+") =>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ decode("abcde10+10*10+10x") =>abcde++++++++++**********++++++++++xxxxxxxxxx decode("\\") =>\ decode("\1\2\3") =>123 decode("13\7x") =>7777777777777x decode("5\\") =>\\\\\ decode("4\12\23\3") =>111122333 decode("4\\2\3") =>\\\\33 NOTE: To represent a single backslash, it’s necessary to place double backslashes (\\) in the input string to obtain the desired in...

Non-decreasing Array - LeetCode

Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n). Example 1: Input: [4,2,3] Output: True Explanation: You could modify the first 4 to 1 to get a non-decreasing array.   Example 2: Input: [4,2,1] Output: False Explanation: You can't get a non-decreasing array by modify at most one element. Note: The n belongs to [1, 10,000]. Source: LeetCode At first glance, it looks like an easy and straightforward problem, but believe me it's greedy problem. In the problem, you are allowed to make atmost "one" modification to make a non-decreasing array. Nondecreasing means that every element is greater than or equal to the one before it e.g. [1,3,4,4,5,6,9]. For example, [2,2,3,2,4] can this become non-decreasing? Yes, by replacing 3 with 2 =>[2,2,2,2,4]. What about this:...

Invert Binary Search Tree

Invert a binary tree. Example: 4 / \ 2 7 / \ / \ 1 3 6 9   to   4 / \ 7 2 / \ / \ 9 6 3 1  4 / \ 2 7 / \ / \ 1 3 6 9   Trees are crucial data structure in Computer Science. Often trees related problems are solved using recursion as it provides an elegant solution in this particular problem at least. The basic terminology to solve this problem is to swap the left and right values, if you work on the tree from the bottom the to the top swapping the left and right node, the tree will be inverted. Let's go through an example: You can start from left or right. So, starting from the left we have   2 2 (swap the left and right node) / \ => / \ 1 3 3 1   7 7 (similarly, on the right sub-tree) / \ => / \ 6 9 9 6    Which gives,   4 / \ 2 7 / \ / \ ...