Home > Back-end >  Inorder traversal is working when creating a separate function, but not working when creating a sing
Inorder traversal is working when creating a separate function, but not working when creating a sing

Time:10-10

The below code works for inorder traversal-

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        solve(res,root);
        return res;
    }
    
    private void solve(List<Integer> res, TreeNode root){
        if(root == null) return;
    
        solve(res, root.left);
        res.add(root.val);
        solve(res, root.right);
    }
}

But why are we writing the solve as a different function? Why can't we write only one function such as:-

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
     List<Integer> list= new ArrayList<>();
     if(root==null)
     {
         return list;
     }

     inorderTraversal(list,root.left);
     list.add(root.val);
     inorderTraversal(list,root.right);
     return list;

    }
 }

The above code does not works. Why is that so? Please ignore incase of any typo/syntax error.

CodePudding user response:

Your alternative could work, but it has some issues:

  • The function takes one argument, but you recursively call it with two arguments
  • The function returns a list, but you ignore that returned list when making the recursive call

Here is how it could work:

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
         if(root==null)
         {
             return new ArrayList<Integer>();
         }
         List<Integer> list = inorderTraversal(root.left);
         list.add(root.val);
         list.addAll(inorderTraversal(root.right));
         return list;
    }
}
  • Related