Binary Tree Inorder Traversal LeetCode Solution

Here, We see Binary Tree Inorder Traversal LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Binary Tree Inorder Traversal LeetCode Solution

Binary Tree Inorder Traversal LeetCode Solution

Problem Statement

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]

Binary Tree Inorder Traversal Leetcode Solution C++

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> nodes;
        stack<TreeNode*> todo;
        while (root || !todo.empty()) {
            while (root) {
                todo.push(root);
                root = root -> left;
            }
            root = todo.top();
            todo.pop();
            nodes.push_back(root -> val);
            root = root -> right;
        }
        return nodes;
    }        
};Code language: PHP (php)

Binary Tree Inorder Traversal Leetcode Solution Java

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> list = new ArrayList<Integer>();
    dfsTraversal(list, root);
    return list;
}

private boolean dfsTraversal(List<Integer> list, TreeNode root) {
    if(root == null){
        return true;
    }
    if(dfsTraversal(list, root.left)){
        list.add(root.val);
    }
    return dfsTraversal(list, root.right);   
    }
}Code language: PHP (php)

Binary Tree Inorder Traversal Leetcode Solution JavaScript

var inorderTraversal = function(root) {
  const stack = [];
  const res = [];

  while (root || stack.length) {
    if (root) {
      stack.push(root);
      root = root.left;
    } else {
      root = stack.pop();
      res.push(root.val);
      root = root.right;
    }
  }
  return res;    
};Code language: JavaScript (javascript)

Binary Tree Inorder Traversal Leetcode Solution Python

class Solution(object):
    def inorderTraversal(self, root):
        result, stack = [], [(root, False)]

        while stack:
            cur, visited = stack.pop()
            if cur:
                if visited:
                    result.append(cur.val)
                else:
                    stack.append((cur.right, False))
                    stack.append((cur, True))
                    stack.append((cur.left, False))

        return result
Scroll to Top