Binary Tree-2
Binary Tree-2
Binary tree-2
Prerequisites:
Understanding of basic data structures like arrays and linked lists
Understanding of recursion
Proficiency in a C++ programming language
Today's Checklist:
Traversals in Tree (Preorder, Inorder, Postorder) [Leetcode-144, 94, 145
How recursion works on tree
Print elements of nth leve
Level Order Traversal [Leetcode-102
Level Order Traversal (Using Queue
Construct Tree from Level Order Traversal
Output: [1,2,3]
Example 2:
Input: root = []
Output: []
Java
C++ &+ DSA
DSA
Code:
class Solution {
public:
if(root==NULL)return;
ans.push_back(root->val);
preorder(root->left,ans);
preorder(root->right,ans);
vector<int> ans;
preorder(root,ans);
return ans;
};
Explanation:
Time Complexity: O(N) - Linear time complexity since each node is visited once.
Space Complexity:
Worst Case: O(N) - Due to the call stack in the case of a skewed tree.
Average Case (Balanced Tree): O(log N) - Height of the call stack in a balanced tree.
Example 1:
Java
C++ &+ DSA
DSA
Input: root = [1,null,2,3]
Output: [1,3,2]
Example 2:
Input: root = []
Output: []
Example 3:
Output: [1]
Code:
class Solution {
public:
vector<int> result;
helper(root, result);
return result;
if (root != nullptr) {
helper(root->left, result);
result.push_back(root->val);
helper(root->right, result);
};
Explanation:
Time Complexity: O(N) - Linear time, where N is the number of nodes in the binary tree. Each node is visited
once during the inorder traversal.
Space Complexity: O(N) - Linear space, where N is the number of nodes in the binary tree. The space is used
for the call stack during recursion and the result vector storing node values.
Java
C++ &+ DSA
DSA
Postorder Traversal In Tree [Leetcode-145]
Given the root of a binary tree, return the postorder traversal of its nodes' values.
Example 1:
Output: [3,2,1]
Example 2:
Input: root = []
Output: []
Example 3:
Output: [1]
Code:
class Solution {
public:
if(root==NULL){
return ;
if(root->left){
solver(root->left,ans);
if(root->right){
solver(root->right,ans);
ans.push_back(root->val);
vector<int> ans;
solver(root,ans);
return ans;
};
Java
C++ &+ DSA
DSA
Explanation:
Time Complexity: O(N) - linear time complexity, as each node is visited once during the postorder traversal.
Space Complexity: O(N) - linear space complexity due to the recursive call stack and the vector (ans) storing
node values.
Explanation:
Base Case:Define a simple scenario where the function returns a result directly, often involving leaf nodes or
empty subtrees
Recursive Step:Break down the problem into smaller sub-problems by applying the function recursively to
each subtree
Combining Results:Combine results from recursive calls to get the final result for the current node or level of
the tree
This approach is efficient and often leads to concise code, as each node is treated as the root of its own
subtree.
Java
C++ &+ DSA
DSA
Output: 4 5 6
Explanation: All the nodes present in level 3 of above binary tree from left to right are 4, 5, and 6.
Code:
#include <bits/stdc++.h>
struct Node {
int data;
};
// Base Case
if (root == NULL) {
return;
if (K == level) {
temp->data = data;
return temp;
Java
C++ &+ DSA
DSA
Explanation:
The code defines a Node structure for a binary tree with data, left, and right pointers
printNodes is a recursive function to print nodes at a specific level (K) in a binary tree using DFS
Base case: If the current node is NULL, return
Recursively calls printNodes for the left and right subtrees, incrementing the level
Prints the data of the current node if its level matches the target level (K)
newNode creates a new tree node with the given data
Example usage involves creating a binary tree and calling printNodes with the root and desired level (K)
Assumes a 0-indexed tree where the root is at level 0
The code focuses on depth-first traversal and level-based printing of nodes in a binary tree.
Space Complexity: O(H) - linear space, where H is the height of the binary tree (max depth of recursive call
stack).
Explanation:
Base Case:Define a simple scenario where the function returns a result directly, often involving leaf nodes or
empty subtrees
Recursive Step:Break down the problem into smaller sub-problems by applying the function recursively to
each subtree
Combining Results:Combine results from recursive calls to get the final result for the current node or level of
the tree
This approach is efficient and often leads to concise code, as each node is treated as the root of its own
subtree.
Java
C++ &+ DSA
DSA
Binary Tree Level Order Traversal [Leetcode-102]
Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by
level).
Example 1:
Output: [[3],[9,20],[15,7]]
Example 2:
Output: [[1]]
Example 3:
Input: root = []
Output: []
Code:
class Solution {
public:
vector<vector<int>> result;
int count = 0;
return result;
private:
if(root == NULL){
return ;
result.push_back(vector<int>());
result[count].push_back(root->val);
count++;
}
};
Java
C++ &+ DSA
DSA
Explanation:
The space complexity depends on the maximum height of the call stack during recursion.
In the worst case (skewed tree), the height is N, resulting in O(N) space complexity.
In the average case (balanced tree), the height is log(N), resulting in O(log(N)) space complexity.
Example 1:
Java
C++ &+ DSA
DSA
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Example 2:
Output: [[1]]
Example 3:
Input: root = []
Output: []
Code:
class Solution {
public:
vector<vector<int>>ans;
if(root==NULL)return ans;
queue<TreeNode*>q;
q.push(root);
while(!q.empty()){
int s=q.size();
vector<int>v;
for(int i=0;i<s;i++){
TreeNode *node=q.front();
q.pop();
if(node->left!=NULL)q.push(node->left);
if(node->right!=NULL)q.push(node->right);
v.push_back(node->val);
ans.push_back(v);
return ans;
};
Explanation:
Objective: Perform level-order traversal of a binary tree and return the result
Data Structures: ans (2D vector for traversal outcome), q (Queue for level-order traversal)
Traversal Process: Enqueue root into q; while q not empty, process each level, enqueue children, and append
values to ans
Return: Final 2D vector ans representing the level-order traversal.
Java
C++ &+ DSA
DSA
Time Complexity: O(N) where N is the number of nodes in the binary tree. Each node is visited once.
Space Complexity: O(M) where M is the maximum number of nodes at any level in the binary tree. In the worst
case, the queue (q) will store all nodes at a single level.
Code:
#include <bits/stdc++.h>
struct Node {
int key;
Node* left;
Node* right;
};
n->key = value;
n->left = NULL;
n->right = NULL;
return n;
queue<Node *>& q)
if (root == NULL)
root = node;
q.front()->left = node;
else {
q.front()->right = node;
q.pop();
q.push(node);
return root;
Java
C++ &+ DSA
DSA
{
queue<Node*> q;
return root;
if (root == NULL)
return;
queue<Node*> n;
n.push(root);
while (!n.empty()) {
if (n.front()->left != NULL)
n.push(n.front()->left);
if (n.front()->right != NULL)
n.push(n.front()->right);
n.pop();
Explanation:
The code defines a binary tree structure with a level-order insertion method
It uses a queue to construct the binary tree in a level-order manner
The createTree function builds a binary tree from an array of integers
The levelOrder function prints the nodes of the tree in level-order traversal
The code is a concise illustration of binary tree construction and level-order traversal.
Time Complexity:
The time complexity for inserting each element into the binary tree is O(1) on average because each node is
inserted once.
The createTree function iterates through the array of size n, resulting in a time complexity of O(n).
The levelOrder function performs a level-order traversal, visiting each node once, leading to a time complexity
of O(n).
Space Complexity:
The space complexity is O(n) as the queue can store up to n nodes during the construction of the binary tree.
The queue is the primary contributor to space usage, and its size is proportional to the number of nodes in the
binary tree.
The space complexity is determined by the maximum number of nodes at any level in the binary tree during
construction.
Java
C++ &+ DSA
DSA