Binary Tree Inorder Traversal LeetCode Solution
Binary Tree Inorder Traversal LeetCode Solution :
Given the root of a binary tree, return the inorder traversal of its nodes’ values.
Example :
Input: root = [1,null,2,3]
Output: [1,3,2]
Binary Tree Inorder Traversal LeetCode Solution :
Constraints :
- The number of nodes in the tree is in the range [0, 100].
- -100 <= Node.val <= 100
Example 2:
- Input: root = []
- Output: []
Point to note while solving such probs
When solving problems involving binary trees, especially traversal-related problems like inorder traversal:
Understand the problem requirements and constraints.
Choose the appropriate traversal method (inorder, preorder, postorder) based on the problem's needs.
Implement a recursive or iterative approach for tree traversal.
Maintain a data structure (e.g., a list or vector) to store the results.
Approach for Binary Tree Inorder Traversal LeetCode Solution :
Start with an empty vector to store the result.
Recursively traverse the left subtree, adding its values to the result.
Add the value of the current node to the result.
Recursively traverse the right subtree, adding its values to the result.
Return the result vector, which now contains the values of the binary tree in ascending order due to the inorder traversal.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Code for Validate Binary Search Tree LeetCode Solution : :
C++
Java
Python
C++
class Solution { public: vectorinorderTraversal(TreeNode* root) { vector ans; if (root == NULL) return ans; vector left = inorderTraversal(root->left); ans.insert(ans.end(), left.begin(), left.end()); ans.push_back(root->val); vector right = inorderTraversal(root->right); ans.insert(ans.end(), right.begin(), right.end()); return ans; } };
Java
class Solution { private Listres = new ArrayList<>(); public List inorderTraversal(TreeNode root) { traverse(root); return res; } private void traverse(TreeNode root) { if (root == null) { return; } traverse(root.left); res.add(root.val); traverse(root.right); } }
Python
class Solution: def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: st = [] res = [] while root or st: while root: st.append(root) root = root.left root = st.pop() res.append(root.val) root = root.right return res
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment