In this post, we are going to solve the 144. Binary Tree Preorder Traversal problem of Leetcode. This problem 144. Binary Tree Preorder Traversal is a Leetcode easy level problem. Let’s see the code, 144. Binary Tree Preorder Traversal – Leetcode Solution.
Problem
Given the root
of a binary tree, return the preorder traversal of its nodes’ values.
Example 1 :
Input: root = [1,null,2,3]
Output: [1,2,3]
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
Now, let’s see the code of 144. Binary Tree Preorder Traversal – Leetcode Solution.
Binary Tree Preorder Traversal – Leetcode Solution
144. Binary Tree Preorder Traversal – Solution in Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public void preOrder(TreeNode root, List<Integer> ans){ if(root == null) return; ans.add(root.val); preOrder(root.left,ans); preOrder(root.right,ans); } public List<Integer> preorderTraversal(TreeNode root) { List<Integer> ans = new ArrayList<Integer>(); preOrder(root,ans); return ans; } }
144. Binary Tree Preorder Traversal – Solution in C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> v; preTraversal(root, v); return v; } void preTraversal(TreeNode* root, vector<int>& v){ if(!root) return; v.push_back(root->val); preTraversal(root->left, v); preTraversal(root->right, v); } };
144. Binary Tree Preorder Traversal – Solution in Python
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def preorderTraversal(self, root): res = [] self.dfs(root, res) return res def dfs(self, root, res): if root: res.append(root.val) self.dfs(root.left, res) self.dfs(root.right, res)
Note: This problem 144. Binary Tree Preorder Traversal is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.