Binary Tree Inorder Traversal Leetcode Solution

In this post, we are going to solve the Binary Tree Inorder Traversal Leetcode Solution problem of Leetcode. This Leetcode problem is done in many programming languages like C++, Java, and Python.

Binary Tree Inorder Traversal Leetcode Solution
Binary Tree Inorder Traversal Leetcode Solution

Problem

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]

Constraints:

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

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

Now, lets see the leetcode solution of Binary Tree Inorder Traversal Leetcode Solution.

Binary Tree Inorder Traversal Leetcode Solution in Python

class Solution:
  def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
    ans = []
    stack = []

    while root or stack:
      while root:
        stack.append(root)
        root = root.left
      root = stack.pop()
      ans.append(root.val)
      root = root.right

    return ans

Binary Tree Inorder Traversal Leetcode Solution in CPP

class Solution {
 public:
  vector<int> inorderTraversal(TreeNode* root) {
    vector<int> ans;
    stack<TreeNode*> stack;

    while (root || !stack.empty()) {
      while (root) {
        stack.push(root);
        root = root->left;
      }
      root = stack.top(), stack.pop();
      ans.push_back(root->val);
      root = root->right;
    }

    return ans;
  }
};

Binary Tree Inorder Traversal Leetcode Solution in Java

class Solution {
  public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> ans = new ArrayList<>();
    Deque<TreeNode> stack = new ArrayDeque<>();

    while (root != null || !stack.isEmpty()) {
      while (root != null) {
        stack.push(root);
        root = root.left;
      }
      root = stack.pop();
      ans.add(root.val);
      root = root.right;
    }

    return ans;
  }
}

Note: This problem Binary Tree Inorder Traversal is generated by Leetcode but the solution is provided by Chase2learn This tutorial is only for Educational and Learning purposes.

NEXT: Unique Binary Search Trees II Leetcode Solution

Sharing Is Caring

Leave a Comment