Problem: Binary Tree Inorder Traversal

image.png

Constraints:

The number of nodes in the tree is in the range [0, 100]. -100 <= Node.val <= 100

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {


        if(root==null)return new ArrayList<Integer>();

        List<Integer> list=new ArrayList();       
        Stack<TreeNode> stack=new Stack();

        TreeNode ptr=root;

      while(1>0){      
          if(ptr!=null){
             stack.push(ptr);
             ptr=ptr.left;
        }
        else{
            if(stack.size()==0)break;
            //since ptr was null re-assigning it to the root of current subtree
            //then adding to the list and movingto right
            ptr=stack.pop();
            list.add(ptr.val);
            ptr=ptr.right;
       }

     }        
         return list;

    }
}

image.png