Skip to main content

Command Palette

Search for a command to run...

Problem: Binary Tree Inorder Traversal

Published
•1 min read•View as Markdown
A

({MERN Stack Developer at mackph}) | <Ex-Internshala Student Partner(ISP 16)> | <5 star coder at Hackerrank> | <Self employed at Mackph> | <GSSoC '22 Contributor> | <Ex-Campus Ambassador at International MUN>

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

More from this blog

mackph's blog

40 posts