Binary Tree Inorder Traversal

Hi Geeks! In this article, we going to look at the Binary Tree in Inorder Traversal.

Given a binary tree, return the inorder traversal of its nodes’ values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]

Follow up: Recursive solution is trivial, could you do it iteratively?

Solution – Recursive approach

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    IList<int> list;
    public IList<int> InorderTraversal(TreeNode root) {
        list = new List<int>();
        FindInOrderTraversal(root,list);
        return list;
    }
    public void FindInOrderTraversal(TreeNode root,IList<int> list)
    {
        if(root != null){
            FindInOrderTraversal(root.left,list);
            list.Add(root.val);
            FindInOrderTraversal(root.right,list);
        }
        
    }
}

But in our given problem, they asked to solve in iterative way. Let’s do that now.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public IList<int> InorderTraversal(TreeNode root) {
        var list = new List<int>();
        Stack<TreeNode> s = new Stack<TreeNode>();
        TreeNode curNode = root;
        
        while(s.Count != 0 || curNode != null)
        {
            while(curNode != null)
            {
                s.Push(curNode);
                curNode = curNode.left;
            }
            if(s.Count > 0)
            {
                curNode = s.Pop();
                list.Add(curNode.val);
                curNode = curNode.right;
            }
        }
        return list;
    }
}

In our next post, we going to look at the Binary Tree Preorder Traversal.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s