LeetCode #94 Binary Tree Inorder Traversal Solution & Explanation

LeetCode Problem

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

LeetCode#94 Examples
LeetCode#94 Constraints

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


Solution

There have three common different ways the binary tree can be traversed .

Which are Inorder, Preorder and Postorder.

Inorder traversal : Left Node ➡ Parent Node ( Root ) ➡ Right Node

C# Solution

Solution1

public class Solution {
    
    public IList<int> InorderTraversal(TreeNode root) {
        List<int>res = new List<int>();
        if(root == null)
        {
            return res;
        } 
        return Inorder(res,root);
    }
    
    public IList<int> Inorder(IList<int> res,TreeNode root)
    {    
        if(root.left!=null)
        {
           res = Inorder(res,root.left); 
        }
        
        res.Add(root.val);
        
        if(root.right!=null)
        {
            res = Inorder(res,root.right); 
        }
        
        return res;
    }
}

Java Solution

Solution1

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer>res = new ArrayList<Integer>();
        if(root == null)
        {
            return res;
        } 
        return Inorder(res,root);
    }
    
    public List<Integer> Inorder(List<Integer> res,TreeNode root)
    {    
        if(root.left!=null)
        {
           res = Inorder(res,root.left); 
        }
        
        res.add(root.val);
        
        if(root.right!=null)
        {
            res = Inorder(res,root.right); 
        }
        
        return res;
    }
}

Runtime : 0ms、0ms、0ms

Python3 Solution

Solution1

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
    
        def Inorder(root):
            if(root.left != None):
                Inorder(root.left)

            res.append(root.val)

            if(root.right != None):
                Inorder(root.right)
        
        res = []
        if(root == None):
            return res
        
        Inorder(root)
        return res

JavaScript Solution

Solution1

var inorderTraversal = function(root) {
    res = [];
    if(root == undefined)
    {
        return res;
    }
    return Inorder(res,root);
};

function Inorder(res,root)
{
    if(root.left!=undefined)
    {
       res = Inorder(res,root.left); 
    }

    res.push(root.val);

    if(root.right!=undefined)
    {
        res = Inorder(res,root.right); 
    }

    return res; 
}

Conclusion

🧡If my solution helps, that is my honor!

If you got any problem about the explanation, please feel free to let me know

The problem link : Binary Tree Inorder Traversal – LeetCode

Similar problems : Zyrastory.com – LeetCode #144 Binary Tree Preorder Traversal

Latest Post

Leave a Reply

Your email address will not be published. Required fields are marked *