diff --git a/C++/Binary-Tree-Level-Order-Traversal.cpp b/C++/Binary-Tree-Level-Order-Traversal.cpp new file mode 100644 index 00000000..2a3e1d2b --- /dev/null +++ b/C++/Binary-Tree-Level-Order-Traversal.cpp @@ -0,0 +1,61 @@ +/* +Problem: +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: +Input: root = [3,9,20,null,null,15,7] +Output: [[3],[9,20],[15,7]] + +Example 2: +Input: root = [1] +Output: [[1]] + +Example 3: +Input: root = [] +Output: [] + +Constraints: +The number of nodes in the tree is in the range [0, 2000]. +-1000 <= Node.val <= 1000 +*/ + + +/* +Space Complexity : O(N) +Time Complexity : O(N) +Difficulty level : Medium +*/ + +class Solution { +public: + void fun( map>&mp, TreeNode* root, int level) +{ + if(!root) + return; + + mp[level].push_back(root->val); + + fun(mp,root->left,level+1); + fun(mp,root->right,level+1); + +} + + vector> levelOrder(TreeNode* root) { + vector>v; + if(!root) + return v; + + map>mp; + int level=0; + fun(mp,root,level); + auto it=mp.begin(); + while(it!=mp.end()) + { + v.push_back(it->second); + it++; + } + + return v; + + } +}; diff --git a/README.md b/README.md index e0486c1a..bcd3ee1a 100644 --- a/README.md +++ b/README.md @@ -254,6 +254,7 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu | 968 | [Binary Tree Cameras](https://leetcode.com/problems/binary-tree-cameras/) | [C++](./C++/Binary-Tree-Cameras.cpp) | _O(n)_ | _O(logn)_ | Hard | Binary Tree, Dynamic Programming | | 98 | [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/) | [Javascript](./JavaScript/98.Validate-Binary-Search-Tree.js) | _O(log(n))_ | _O(log(n))_ | Medium | Binary Tree | | 684 | [Redundant Connection](https://leetcode.com/problems/redundant-connection/) | [Java](./Java/Redundant-Connection/redundant-connection.java) | _O(N)_ | _O(N)_ | Medium | Tree, Union Find | +| 102 | [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/) |[C++](./C++/Binary-Tree-Level-Order-Traversal.cpp)| _O(n)_ | _O(n)_ | Medium | Binary Tree, map | |