LeetCode #144 Binary Tree Preorder Traversal Solution & Explanation

LeetCode Problem

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

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.

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

C# Solution

Solution1

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

Java Solution

Solution1

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

Python3 Solution

Solution1

class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        
        def Preorder(root):
            res.append(root.val)
            
            if(root.left != None):
                Preorder(root.left)

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

JavaScript Solution

Solution1

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

function Preorder(res,root)
{
    res.push(root.val);
    
    if(root.left!=undefined)
    {
       res = Preorder(res,root.left); 
    }

    if(root.right!=undefined)
    {
        res = Preorder(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 Preorder Traversal – LeetCode

Similar problems : Zyrastory.com – LeetCode #94 Binary Tree Inorder Traversal

Latest Post

Leave a Reply

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