recursiontreeinorder

Inorder traversal is working when creating a separate function, but not working when creating a single function. Why?


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.


Solution

  • Your alternative could work, but it has some issues:

    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;
        }
    }