Accepted , but using a static ArrayList<Integer>, is that allowed?


  • 0
    W
    public class Solution {
    ArrayList<Integer> res=new ArrayList<Integer>();
    public ArrayList<Integer> postorderTraversal(TreeNode root) {
      if(root==null)
      return res;
      postorderTraversal(root.left);
      postorderTraversal(root.right);
      res.add(root.val);
      return res;
    }
    

    }


  • 3
    M

    Yes, this is allowed, but there are a couple things you should pay attention to. First, you could do the same thing by passing the ArrayList as a parameter into a helper function and it would work the same way, looking like this:

    public class Solution{
      public ArrayList<Integer> postorderTraversal(TreeNode root){
        return post(root, new ArrayList<Integer>());
      }
      public ArrayList<Integer> post(TreeNode root, ArrayList<Integer> list){
        if(root==null)
          return list;
        post(root.left,list);
        post(root.right,list);
        list.add(root.val);
        return list;
      }
    |
    

    Second, as the problem said, a recursive solution is trivial. The real aim is to find the iterative solution to the problem. Good luck with your future attempts.


  • 0
    Y

    I think the point of this problem is to solve it iteratively...


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.