94. Binary Tree Inorder Traversal

Sukanya Bharati
2 min readNov 12, 2021

(Solution to LeetCode easy question)

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

Example 1:

Input: root = [1,null,2,3]
Output: [1,3,2]

Example 2:

Input: root = []
Output: []

Example 3:

Input: root = [1]
Output: [1]

Example 4:

Input: root = [1,2]
Output: [2,1]

Example 5:

Input: root = [1,null,2]
Output: [1,2]

Constraints:

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

What do you mean by level order traversal? Well, it is as simple, you have to first traverse the left then the root, and then the right.

It is simple right? Now let us look at the code now.

class Solution {
public:
vector<int>ans;
vector<int> inorderTraversal(TreeNode* root) {
if(root==NULL)
return ans;
inorderTraversal(root->left);
ans.push_back(root->val);
inorderTraversal(root->right);
return ans;
}
};

But do you know one trick to check if you have done it right to not? Just check the printed vector, all the elements must be in increasing order.

So the time complexity here will be O(n) and space complexity will be O(n).

I hope this is clear to you. Till then keep coding & keep learning!! πŸ’»πŸ™Œ

Since you enjoyed reading my blog , why not buy me a coffee and supoort my work here!! https://www.buymeacoffee.com/sukanyabharati β˜•

--

--

Sukanya Bharati

A happy , motivated & a curious soul if you end up finding me 😎😁.