L14. Maximum Depth in Binary Tree | Height of Binary Tree | C++ | Java

  Рет қаралды 338,590

take U forward

take U forward

Күн бұрын

Пікірлер
@takeUforward
@takeUforward 3 жыл бұрын
Please likeeee, shareeee and subscribeeeeeeee :) Also follow me at Insta: Striver_79
@arishsheikh3000
@arishsheikh3000 2 жыл бұрын
Java code is not passing test cases
@himanshuagrawal8012
@himanshuagrawal8012 2 жыл бұрын
int maxDepthIterative (BinaryTreeNode * root) { if(root == NULL)return 0; int ans = 0; queue pendingNodes; pendingNodes.push(root); while(!pendingNodes.empty()) { int size = pendingNodes.size(); ans++; for(int i=0;ileft)pendingNodes.push(front->left); if(front->right)pendingNodes.push(front->right); } } return ans; }
@SatyamEdits
@SatyamEdits 2 жыл бұрын
Bhaiya description me question galat hai......
@chinmayraichur8984
@chinmayraichur8984 Жыл бұрын
@@arishsheikh3000 chal rha hai bhai Java code
@fffooccc9801
@fffooccc9801 Жыл бұрын
if(root==NULL) return 0; queue q; map mp; q.push({root,0}); while(!q.empty()){ int level =q.front().second; TreeNode *s=q.front().first; mp[level]=s->val; //gets overriden q.pop(); if(s->left) q.push({s->left,level+1}); if(s->right) q.push({s->right,level+1}); } return (--mp.end())->first+1; //applied the bottom view concept and returned the key/level at last of map
@nikunjgarg3754
@nikunjgarg3754 3 жыл бұрын
Level Order Traversal Approach in C++. int maxDepth(TreeNode* root) { int depth = 0; if (root == NULL) return depth; queue q; q.push(root); while (!q.empty()) { int size = q.size(); depth++; for (int i = 0; i < size; i++) { TreeNode* temp = q.front(); q.pop(); if (temp -> left != NULL) q.push(temp -> left); if (temp -> right != NULL) q.push(temp -> right); } } return depth; }
@chiragmehta2955
@chiragmehta2955 Жыл бұрын
thanx man
@UECSoumyaRay
@UECSoumyaRay Жыл бұрын
Don't even need the depth variable bro. Can return the ans.size() in the BFS standard code.
@RohitRaj-hl6ji
@RohitRaj-hl6ji Жыл бұрын
@@UECSoumyaRay then we need to 2 ds to store the nodes using count don't even need it but its personal choice to select favourite method
@btOOVipulJarial
@btOOVipulJarial Жыл бұрын
@@UECSoumyaRay yes but why to take an extra data structure unnecesarily
@gpraveen669
@gpraveen669 Жыл бұрын
Good bro keep it up
@jayadubey_22
@jayadubey_22 3 жыл бұрын
writing recursive code on your own is difficult. But by the the dry run i can imagine somehow😅thankyou so much really doing great work🙌
@raghavchawla1658
@raghavchawla1658 Жыл бұрын
it's been a year so maybe you can tell me how you managed to come up with recursive solutions on your own?
@nitpBlogs
@nitpBlogs Жыл бұрын
@@raghavchawla1658 same question
@SohelDarwajkar
@SohelDarwajkar 11 ай бұрын
​@@nitpBlogsFollow Aditya Verma's Recursion Playlist and until the end of the playlist The recursion in trees will be like a cakewalk ..
@Tbm4545
@Tbm4545 27 күн бұрын
To get the solution by ur own go and watch first 5 videos of recursion playlist, even u will oslve by hr own​@@raghavchawla1658
@dhruvgarg8106
@dhruvgarg8106 8 күн бұрын
@@raghavchawla1658 it's been a year so maybe you can tell me how you managed to come up with recursive solutions on your own?
@sheetalbhattamisra2000
@sheetalbhattamisra2000 Жыл бұрын
Tree has not been that easy before your video ....thanks so much for a2z DS ....the best video on KZbin
@udayprakashharsh2805
@udayprakashharsh2805 Жыл бұрын
I had a different approach I used pair inside queue to cal the height to avoid that extra for loop int maxDepth(struct Node* root){ queue pq; int maxi = -1; pq.push(make_pair(root, 1)); while(!pq.empty()){ auto temp = pq.front(); pq.pop(); maxi = max(temp.second, maxi); // coutright, temp.second + 1)); } return maxi; }
@cursed_nerd
@cursed_nerd Жыл бұрын
SC ke to lag gaye honge
@toontime7663
@toontime7663 Жыл бұрын
@@cursed_nerd why would the SC be more in this approach ? i think it will the same as in the inner loop using queue solution... correct me if i am wrong
@zee_desai
@zee_desai 7 ай бұрын
Python one liner: def height(node): return 0 if not node else max(height(node.left), height(node.right) )+ 1
@SaiSumanthKovuru
@SaiSumanthKovuru Жыл бұрын
Greatest series ever seen on Trees
@Reyna-yj6vo
@Reyna-yj6vo 5 ай бұрын
with pre-order int f(TreeNode *node, int k){ if(node==NULL) return k; k++; int l = f(node->left,k); int r = f(node->right,k); return max(l,r); }
@modigautam7009
@modigautam7009 6 күн бұрын
Using level order int maxDepth(TreeNode* root) { if(!root)return 0; queueq; q.push(root); int height = 0; while(!q.empty()) { height++; int size = q.size(); for(int i=0;ileft)q.push(curr->left); if(curr->right)q.push(curr->right); } } return height; }
@lifehustlers164
@lifehustlers164 Жыл бұрын
Completed 15/54(27% done) !!!
@rakshayadav1892
@rakshayadav1892 2 жыл бұрын
Python code: class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: def dfs(root,depth): if not root: return depth return max(dfs(root.left,depth+1),dfs(root.right,depth+1)) return dfs(root,0)
@111rhishishranjan2
@111rhishishranjan2 Жыл бұрын
only c++, no python here
@amanpreetsinghbawa1600
@amanpreetsinghbawa1600 2 ай бұрын
I would recommend everyone especially the ones which are beginners to DSA, to watch the tree series only after going through his recursion & backtracking series. Much of the problems will be self solvable, Thanks striver😄
@akshitrajputhere
@akshitrajputhere Ай бұрын
Damn
@Dibyadipan
@Dibyadipan 19 күн бұрын
Outstanding dry run and explanation. Thank you Striver! ❤️
@Kartik-s8r
@Kartik-s8r 6 ай бұрын
LEVEL ORDER TRAVERSAL (C++, without using any extra variable) Simply the number. of levels is height So we can get number of levels by directly getting size of the resultant vector class Solution { public: int maxDepth(TreeNode* root) { vector ans; if(!root) return 0; queue q; q.push(root); while(!q.empty()) { vector level; int n = q.size(); for(int i=0; ival); if(node->left) q.push(node->left); if(node->right) q.push(node->right); } ans.push_back(level); } return ans.size(); } };
@kushalchakraborty6970
@kushalchakraborty6970 2 жыл бұрын
For level order just keep a cnt variable and do ++ within the loop
@thanosprish1730
@thanosprish1730 2 жыл бұрын
i have discovered you through Love Babbar's one of the video. And really sir you are great your explanation are are very clear..... you and babbar both are great ...thanks for making free courses.....If possible then please also make a course on full stack development or first only start with frontend
@codding32world50
@codding32world50 2 жыл бұрын
there is code with harry for that.. let strive bhaiya cover toughest part that is noting but DS Algo you can learn fsd from anywhere buddy
@ankit_6378
@ankit_6378 2 жыл бұрын
Level Order Traversal C++ Code: int maxDepth(TreeNode* root) { if (root==NULL) return 0; queue q; q.push(root); int depth=0; while (!q.empty()) { ++depth; int s=q.size(); for (int i=0; ileft) q.push(front->left); if (front->right) q.push(front->right); } } return depth; }
@vardhamanbhandari5644
@vardhamanbhandari5644 Жыл бұрын
u'r teching method is amazing striver, Hands off to your efforts🙌🙌🙌
@nsudhir_here
@nsudhir_here 2 жыл бұрын
Level Oder Traversal method of finding the max depth: int height(struct Node* node) { int height = 1; queue q; q.push({node, height}); while(!q.empty()) { auto p = q.front(); height = p.second; q.pop(); if(p.first->left) { q.push({p.first->left, p.second+1}); } if(p.first->right) { q.push({p.first->right, p.second+1}); } } return height; }
@sumitkanth5349
@sumitkanth5349 2 жыл бұрын
Can you provide recursive code to solve the problem plz
@soumikdutta7867
@soumikdutta7867 3 жыл бұрын
Level Order Traversal Approach in JAVA ->> public int maxDepth(TreeNode root) { if(root == null) return 0 ; Queue q = new LinkedList() ; q.add(root) ; int ans = 0 ; while(!q.isEmpty()) { ans ++ ; int n = q.size() ; for(int i = 0; i< n ; i++) { TreeNode x = q.remove() ; if(x.left != null) q.add(x.left) ; if(x.right != null) q.add(x.right) ; } } return ans ; } // Tree class class TreeNode { int val ; TreeNode left ; TreeNode right ; TreeNode(int val) { this.val = val ; } }
@shivaakrish
@shivaakrish Жыл бұрын
Iterative approach using level order traversal: if(root==null) return 0; //using level order traversal Queue q = new LinkedList(); q.add(root); int height=0; while(!q.isEmpty()){ height++; int size = q.size(); for(int i=0;i
@TheWierdVibe
@TheWierdVibe 2 жыл бұрын
the best series on KZbin!
@nikhilnagrale
@nikhilnagrale 3 жыл бұрын
Level Order Traversal Approach ```class Solution { public: int maxDepth(TreeNode* root) { if (!root) return 0; queue q; q.push(root); int depth = 0; while (!q.empty()) { int size = q.size(); for (int i = 0; i < size; i++) { TreeNode* node = q.front(); q.pop(); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } depth++; } return depth; } };```
@gpraveen669
@gpraveen669 Жыл бұрын
keep it up bro
@nikhilnagrale
@nikhilnagrale Жыл бұрын
@@gpraveen669 it's been a year haven't touch DSA 😂
@sasikumarvm5172
@sasikumarvm5172 3 жыл бұрын
Actually height of node or tree is based on how many edges are connected form node to longest edge path of leaf node. As per your explanation it's counting the number of nodes, so in code we need to change the base case should trun -1 to get correct output, Apart from that your way of teaching is very good
@takeUforward
@takeUforward 3 жыл бұрын
I have solved it according to the question at leetcode :) However depending on the questions, the condition can change and that will work..
@swayamterode4965
@swayamterode4965 Жыл бұрын
(C++) Level Order Traversal: int maxDepth(TreeNode *root) { int height = 0; if (root == NULL) return 0; queue q; q.push(root); while (!q.empty()) { int n = q.size(); // vector < int>level; for (int i = 0; i < n; i++) { auto node = q.front(); q.pop(); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } height++; } return height; }
@faltubaccha.2498
@faltubaccha.2498 5 ай бұрын
Striver man!, thank you for helping me increase my intrest is DS Algo ❤
@mrsmurf911
@mrsmurf911 Жыл бұрын
Using LEVEL ORDER int ans(TreeNode *root){ int res=-1; queueq; q.push(root); while(!q.empty()) { int sz=q.size(); res++; for (int i = 0; i < sz; i++) { TreeNode *nd = q.front(); q.pop(); if (nd->left) q.push(nd->left); if (nd->right) q.push(nd->right); } } return res; }
@Ashishkumar-rb5wj
@Ashishkumar-rb5wj 2 жыл бұрын
for the level order traversal code is as below int maxDepth(TreeNode* root) { queue q; vector ans; q.push(root); if(root==NULL) return 0; int c=0; while(!q.empty()){ int size=q.size(); vector v; for(int i=0;ival); if(x->left!=NULL)q.push(x->left); if(x->right!=NULL)q.push(x->right); } c++; } return c;
@himankpathak4410
@himankpathak4410 2 жыл бұрын
level order traversal if(root==0) { return 0; } int lvl=1; queueq; q.push({root,1}); while(q.empty()==false) { TreeNode * curr=q.front().first; lvl=q.front().second; q.pop(); if(curr->left) q.push({curr->left,lvl+1}); if(curr->right) q.push({curr->right,lvl+1}); } return lvl;
@josephhsia
@josephhsia 10 ай бұрын
What an elegantly simple solution to finding a binary tree in 5 lines of code...
@abhijitbiradar
@abhijitbiradar 2 жыл бұрын
Very beautifully explained. Many Thanks
@akhileshgoswami7699
@akhileshgoswami7699 3 жыл бұрын
best video on maximum Depth in binary tree im commenting before watching coz i Know you make best
@nawabkhan4916
@nawabkhan4916 3 жыл бұрын
great work, and have lots of sponsor ad so that you can provide great videos.
@navyasreepinjala1582
@navyasreepinjala1582 4 ай бұрын
Level Order traversal in Python: def maxDepth(self, root: Optional[TreeNode]) -> int: level = 0 if root == None: return level queue = [root] while queue: n = len(queue) level += 1 for i in range(n): node = queue.pop(0) if node.left: queue.append(node.left) if node.right: queue.append(node.right) return level
@moghalsalwar6803
@moghalsalwar6803 Жыл бұрын
int height(Node node) { // code here int count=0; Queue q=new LinkedList(); q.add(node); while(!q.isEmpty()){ int size=q.size(); int i=0; count=count+1; while(i
@sravan8643
@sravan8643 3 жыл бұрын
5 line solution: int maxDepth(TreeNode* root,int ans=0) { if(root==NULL)return ans; ans+=1; return max(maxDepth(root->left,ans),maxDepth(root->right,ans)); }
@enigmanarratives1
@enigmanarratives1 2 жыл бұрын
int maxDepth(TreeNode* root) { if(root==NULL) return 0; return 1+max(maxDepth(root->left),maxDepth(root->right)); } one line less
@shubh13799
@shubh13799 2 жыл бұрын
Level Order traversal ``` def maxDepth(self, root: Optional[TreeNode]) -> int: if root is None: return 0 queue = deque([root]) height = 0 while queue: height += 1 for i in range(len(queue)): node = queue.popleft() if node.left: queue.append(node.left) if node.right: queue.append(node.right) return height ```
@Ramu9119
@Ramu9119 Жыл бұрын
Iterative Way (In below code I have used deque instead you can also use queue) int height(Node* node) { if(node == NULL) return 0; int count = 0; deque nodes; nodes.push_back(node); while(nodes.size() > 0) { count++; int size = nodes.size(); for(int i=0; ileft != NULL) nodes.push_back(nodes.front()->left); if(nodes.front()->right != NULL) nodes.push_back(nodes.front()->right); nodes.pop_front(); } } return count; }
@purnamritab
@purnamritab Жыл бұрын
Level Order Traversal Approach:(C++) int maxDepth(TreeNode* root) { int level = 0; if(root == NULL){ return level; } queue q; q.push(root); while(!q.empty()){ int size = q.size(); level++; for(int i = 0; i < size; i++){ TreeNode* node = q.front(); q.pop(); if(node -> left){ q.push(node -> left); } if(node -> right){ q.push(node -> right); } } } return level; }
@MultiFacebookers
@MultiFacebookers 2 жыл бұрын
Isn't the height of an empty tree -1 and the height of tree with one node 0? Then shouldn't in this case (1:53) height be 3 but in the video striver said it's 4? Correct me if I'm understanding it wrong.
@phatcat7924
@phatcat7924 2 жыл бұрын
I have the same doubt and to implement this change in the code just return -1 instead of 0 when root == NULL.
@kartikeykeshari2855
@kartikeykeshari2855 2 ай бұрын
i also have same doubt
@rahatsshowcase8614
@rahatsshowcase8614 2 жыл бұрын
The work recursion does is huge and the code is very very cute;
@guneeshvats46
@guneeshvats46 6 ай бұрын
amazing explanation although I had to watch it 3 times but still it was to the point
@DhananjayKumar-vn5tc
@DhananjayKumar-vn5tc 3 жыл бұрын
done using level order traversal bhaiya Queue st=new LinkedList(); if(root==null) return 0; st.add(root); int height=0; while(1==1) { int n=st.size(); if(n==0) return height; height++; while(n>0) { TreeNode temp=st.peek(); st.remove(); if(temp.left!=null) { st.add(temp.left); } if(temp.right!=null) { st.add(temp.right); } n--; } }
@UECSoumyaRay
@UECSoumyaRay Жыл бұрын
Just returning the ans.size() in the BFS code: class Solution { public: int maxDepth(TreeNode* root) { vector ans; if(root == NULL) return 0; queue q; q.push(root); while(!q.empty()){ vector level; int size = q.size(); for(int i=0; i< size; i++){ TreeNode* node = q.front(); q.pop(); if(node-> left != NULL) q.push(node-> left); if(node-> right != NULL) q.push(node-> right); level.push_back(node -> val); } ans.push_back(level); } return ans.size(); } };
@sauravkumardwivedi9384
@sauravkumardwivedi9384 4 ай бұрын
you could have just taken a variable and incremented it at the end of the for loop instead of storing it which is taking extra space
@gouravkumarshaw5467
@gouravkumarshaw5467 2 жыл бұрын
class Solution { public: int maxDepth(TreeNode *root) { if (!root) return 0; queue q; int ans = 0, count = 0; TreeNode *cur; q.push(root); while (!q.empty()) { ans++, count = q.size(); while (count--) { cur = q.front(); if (cur->left != NULL) q.push(cur->left); if (cur->right != NULL) q.push(cur->right); q.pop(); } } return ans; } };
@AnkushMallickOriginal
@AnkushMallickOriginal 4 ай бұрын
Solution: class Solution { public: int maxDepth(TreeNode* root) { vector ans; queue q; if (root == NULL) { return 0; } q.push(root); while (!q.empty()) { int size = q.size(); vector level; for (int i = 0; i < size; i++) { TreeNode* n = q.front(); q.pop(); if (n->right != NULL) { q.push(n->right); } if (n->left != NULL) { q.push(n->left); } level.push_back(n->val); } ans.push_back(level); } return ans.size(); } };
@easycode3189
@easycode3189 2 жыл бұрын
Simple Explanation || Understud 100% || Thanks alot
@sumitkanth5349
@sumitkanth5349 2 жыл бұрын
Can you provide recursive code to solve the problem plz
@pratyushtripathi1728
@pratyushtripathi1728 9 ай бұрын
Understood 😊
@nextnotification9857
@nextnotification9857 9 ай бұрын
int maxDepth(TreeNode* root) { // ITERATIVE USING LEVEL ORDER TRAVERSAL int count=0; if(!root) return count; queueq; q.push(root); while(!q.empty()){ int n=q.size(); for(int i=0;ileft) q.push(f->left); if(f->right) q.push(f->right); } count++; } return count; }
@sniperboy2314
@sniperboy2314 4 ай бұрын
C++ code int maxDepth(TreeNode* root) { if(!root) return 0; int maxLeft = maxDepth(root->left); int maxRight = maxDepth(root->right); return max(maxLeft, maxRight)+1; }
@krishnakanttiwari517
@krishnakanttiwari517 7 күн бұрын
Thank You So Much Sir
@architmishra0057
@architmishra0057 2 ай бұрын
If root is null then return -1 not 0 that's why it gives height as 4 not 3 0:53 .
@nirmalshah8066
@nirmalshah8066 2 жыл бұрын
level order in python : def height(self, root): # code here if not root : return 0 q = [root] res = [] c = 0 while q : for i in range(len(q)) : t = q.pop(0) if t.left : q.append(t.left) if t.right : q.append(t.right) c += 1 return c
@AmitKumar-iu7ze
@AmitKumar-iu7ze Жыл бұрын
class Solution { public int maxDepth(TreeNode root) { if(root == null){ return 0; } Queue q = new LinkedList(); q.offer(root); int h = 0; while(!q.isEmpty()){ int s = q.size(); h++; for(int i = 0; i < s; i++){ TreeNode curr = q.poll(); if(curr.left != null) q.offer(curr.left); if(curr.right != null) q.offer(curr.right); } } return h; } } Console
@vinodpatildev
@vinodpatildev 2 жыл бұрын
int maxDepth(TreeNode* root) { int height = 0; if(root==NULL){return height;} queue q; q.push(root); while(!q.empty()){ int size = q.size(); for(int i=0; ileft){q.push(temp->left);} if(temp->right){q.push(temp->right);} } height++; } return height; }
@sparshsharma3150
@sparshsharma3150 3 жыл бұрын
Amazingly explained! Waiting for more complex problems on trees. Striver bhaiya op!!
@altafshaikh8778
@altafshaikh8778 2 жыл бұрын
def maxDepth(self, root: Optional[TreeNode]) -> int: maxHeight = 0 # Base Case if root is None: return 0 # Create an empty queue # for level order traversal queue = [] # Enqueue Root and initialize height queue.append(root) while(len(queue)): for _ in range(len(queue)): node = queue.pop(0) if node.left is not None: queue.append(node.left) if node.right is not None: queue.append(node.right) maxHeight+=1 return maxHeight
@shaswatkumar362
@shaswatkumar362 2 жыл бұрын
class Solution { public: int maxDepth(TreeNode* root) { if(!root) return 0; queue q; int level = 0; q.push(root); while(!q.empty()) { int size=q.size(); for(int i=0; ileft) q.push(temp->left); if(temp->right) q.push(temp->right); } level++; } return level; } };
@atulk9122
@atulk9122 3 жыл бұрын
again cleared many doubts in one shot
@JATINSHARMA-ei4rb
@JATINSHARMA-ei4rb 3 жыл бұрын
Here is the LEVEL Order Traversal Soln:- def maxDepth(self, root: TreeNode) -> int: if(not(root)): return 0 q=deque() q.append(root) c=0 while(q): l=len(q) for i in range(l): val=q.popleft() if(val.left): q.append(val.left) if(val.right): q.append(val.right) c+=1 #print(q) return c
@AdityaSinghMandloi
@AdityaSinghMandloi 2 ай бұрын
LEVEL ORDER APPROACH class Solution { public: int maxDepth(TreeNode* root) { queue q; int depth=0; if(root==nullptr){ return depth; } q.push(root); while(!q.empty()){ int size=q.size();; depth++; for(int i=0; ileft!=nullptr){ q.push(temp->left); } if(temp->right!=nullptr){ q.push(temp->right); } } } return depth; } };
@sathwikavontela885
@sathwikavontela885 5 ай бұрын
int c=1; if(root==NULL) return 0; queueq; q.push(root); while(!q.empty()) { int n = q.size(); for(int i=0;ileft!=NULL) q.push(cur->left); if(cur->right!=NULL) q.push(cur->right); } if(q.size()>0) c++; } return c; If we use level order traversal then this will the solution.
@cinime
@cinime 2 жыл бұрын
Understood! So amazing explanation as always, thank you very much!!
@divikagrawal9744
@divikagrawal9744 2 жыл бұрын
class Solution { public: int maxDepth(TreeNode* root) { queue que; int n, count=0; if(!root) return 0; que.push(root); while(!que.empty()){ n = que.size(); count+=1; for(int i=0;ileft) que.push(que.front()->left); if(que.front()->right) que.push(que.front()->right); que.pop(); } } return count; } };
@jayatanwani5979
@jayatanwani5979 3 жыл бұрын
class Tree: def __init__(self): self.levels=0 def find_depth(self,root): queue=[root] queue.append(-1) while queue: parent=queue.pop(0) if parent==-1: self.levels+=1 if queue: queue.append(-1) else: if parent.left is not None: queue.append(parent.left) if parent.right is not None: queue.append(parent.right) return self.levels
@gpavansai7207
@gpavansai7207 10 ай бұрын
/* Maximum Depth of Binary Tree using BFS */ public static int maxDeptUsingLevelOrder(Node node) { Queue qu = new ArrayDeque(); qu.add(node); int count=0; while(!qu.isEmpty()) { count++; int n = qu.size(); for(int i=0; i
@per.seus._
@per.seus._ Жыл бұрын
understood dada❤
@prakhardwivedi6966
@prakhardwivedi6966 21 күн бұрын
class Solution { public: int maxDepth(TreeNode* root) { if(root == NULL){ return 0; } queue q; q.push(root); int hight = 0; while(!q.empty()){ int size = q.size(); for(int i=0;ileft) q.push(temp->left); if(temp->right) q.push(temp->right); } hight++; } return hight; } };
@NishantKumar-fq5zr
@NishantKumar-fq5zr 11 ай бұрын
Level Order Traversal in c++ int maxDepth(TreeNode* root) { if(root == NULL)return 0; queueq; q.push(root); int height = 0; while(!q.empty()){ int size = q.size(); for(int i=0; ileft != NULL)q.push(temp->left); if(temp->right != NULL)q.push(temp->right); } height++; } return height; }
@aniketujgare884
@aniketujgare884 2 жыл бұрын
Level Order Traversal Approach c++ int maxDepth(TreeNode* root) { queue q; int depth = 0; if(root != NULL) q.push({root,1}); while(!q.empty()) { auto node = q.front(); depth = node.second; q.pop(); if(node.first->left) q.push({node.first->left, node.second + 1}); if(node.first->right) q.push({node.first->right, node.second + 1}); } return depth; }
@viralpw5846
@viralpw5846 4 ай бұрын
class Solution { public: int maxDepth(TreeNode* root) { // Now we are going to use level order Traversal to solve the above problem if(root == NULL) return 0; queueq; int depth_count = 0; q.push(root); while(!q.empty()){ int size = q.size(); depth_count++; // Now Traverse through all the nodes for(int i=0;ileft != NULL) q.push(curr_node->left); if(curr_node->right != NULL) q.push(curr_node->right); } } return depth_count; } };
@prabhakaran5542
@prabhakaran5542 5 ай бұрын
Understood ❤
@akshayrajsingh2540
@akshayrajsingh2540 Жыл бұрын
level order traversal approach: class Solution { public: int maxDepth(TreeNode* root) { //int maxdepth; if(root==NULL) return 0; queue q; vector ans; q.push(root); while(!q.empty()){ int n=q.size(); vector level; for(int i=0;ileft!=NULL) q.push(node->left); if(node->right!=NULL) q.push(node->right); level.push_back(node->val); } ans.push_back(level); } return ans.size(); } };
@bhavkushwaha
@bhavkushwaha 8 ай бұрын
Thankyou Striver, Understood!
@AI_for_funn
@AI_for_funn 3 жыл бұрын
great video , out of world level explanation
@ganeshkamath89
@ganeshkamath89 2 жыл бұрын
Thanks Striver. It will be interesting to see if this problem can be done with DP technique from DP Series: recursion -> memoization -> tabulation -> space optimization
@pawansingh7430
@pawansingh7430 2 жыл бұрын
DP requires overlapping subproblems this question does not have overlapping subproblems. i.e. we calculate the height of any subtree only once we there is nothing to memoize
@shivanshgupta2518
@shivanshgupta2518 2 жыл бұрын
Level order Traversal:- int count=0; queue q; if(root==NULL){ return NULL; } q.push(root); while(!q.empty()){ int size=q.size(); for(int i=0;ileft!=NULL){ q.push(root->left); } if(root->right!=NULL){ q.push(root->right); } } } return count;
@UECAshutoshKumar
@UECAshutoshKumar Жыл бұрын
Thank you sir
@lavanyaprakashjampana933
@lavanyaprakashjampana933 2 жыл бұрын
we love your content and we love you....🖤
@_hulk748
@_hulk748 Жыл бұрын
Understood sir🙏🙇‍♂❤
@Miraculousbuddy-gh7me
@Miraculousbuddy-gh7me 4 ай бұрын
Kindly post the practice problems as well , Sir .
@neerajkumarmarupalli5313
@neerajkumarmarupalli5313 2 жыл бұрын
Using Level Order Traversal Python code: import queue def maxdepth(root): if root is None: return 0 q = queue.Queue() q.put(root) ans = 0 while q.empty() is False: size = q.qsize() for i in range(size): curr = q.get() if curr.left is not None: q.put(curr.left) if curr.right is not None: q.put(curr.right) ans+= 1 return ans
@Failed5555
@Failed5555 Жыл бұрын
ITERATIVE CODE: class Solution { public: int maxDepth(TreeNode* root) { if(root==NULL)return 0; int height=0; queueq; q.push(root); while(!q.empty()){ int n=q.size(); while(n--){ TreeNode*x=q.front(); q.pop(); if(x->left)q.push(x->left); if(x->right)q.push(x->right); } height++; } return height; } };
@akshitsoneji8944
@akshitsoneji8944 2 жыл бұрын
Javascript Solutions: 1. Level Order Traversal (Runtime beats 49%, ) var maxDepth = function(root) { const Nodes = []; const queue = [] if(root) queue.push(root); const traverse = () => { const levelNodes = [] let length = queue.length if(length === 0) return; while(length--) { const elem = queue.shift(); if(elem === null) break; levelNodes.push(elem.val); if(elem.left) queue.push(elem.left) if(elem.right) queue.push(elem.right) } Nodes.push(levelNodes) traverse(); } traverse() return Nodes.length; }; ======================== 2. Recursive (Runtime beats 90%) var maxDepth = function(root) { const traverse = (elem) => { if(elem === null) return 0; return 1 + Math.max(traverse(elem.left), traverse(elem.right)) } return traverse(root); };
@prarabdhchaturvedi2839
@prarabdhchaturvedi2839 Жыл бұрын
Leverl Order Solution: int max_depth(Node* root){ queue q; q.push(root); int cnt = 0; while(!q.empty()){ Node* node = q.front(); q.pop(); if(node->left!=NULL) q.push(node->left); if(node->right!=NULL) q.push(node->right); if(node->left!=NULL || node->right!=NULL) cnt++; } return cnt; }
@nimisharawat9949
@nimisharawat9949 6 ай бұрын
level order traversal : class Solution { public static int maxDepth(Node root) { int height = 0; Queue q = new LinkedList(); q.offer(root); while(!q.isEmpty()){ int levelNum = q.size(); for(int i=0; i
@sarav-Frontend_Engineer
@sarav-Frontend_Engineer 2 жыл бұрын
Great, explanation. Thank you and keep rocking!
@sumitkanth5349
@sumitkanth5349 2 жыл бұрын
Can you provide recursive code to solve the problem plz
@ganeshjaggineni4097
@ganeshjaggineni4097 5 ай бұрын
NICE SUPER EXCELLENT MOTIVATED
@namansharma5128
@namansharma5128 3 жыл бұрын
7:21 Why is the space complexity O(n) here ? We are not using any extra space🙋‍♂️📢🚨🤔
@takeUforward
@takeUforward 3 жыл бұрын
Recursion stack space
@namansharma5128
@namansharma5128 3 жыл бұрын
@@takeUforward Ohh! got it.
@yashvardhan4980
@yashvardhan4980 3 жыл бұрын
Bhaiya here is the level order traversal solution of this problem... I came with this solution via all traversal video of yours ..thanks for this playlist and happy teacher's day bhaiya... aap humesha khus rahen ye humari tahe dil se khwaihish hain...aur main bhi kolkata rahta hun.. jis din kisi acchi company mein intern lag jaunga aapse milne aaunga 😎😎 class pair{ TreeNode node; int level; pair(TreeNode a,int b) { this.node = a; this.level = b;} } class Solution { public int maxDepth(TreeNode root) { if(root==null) return 0; Queue q = new LinkedList(); q.add(new pair(root,1));int max=1; while(!q.isEmpty()){ int size =q.size(); while(size>0){ pair it = q.remove(); if(it.node.left!=null){ int l = it.level+1; q.add(new pair(it.node.left,l)); max = Math.max(max,l); } if(it.node.right!=null){ int li = it.level+1; q.add(new pair(it.node.right,li)); max = Math.max(max,li); } size--; } } return max; } }
@artitech6668
@artitech6668 2 жыл бұрын
Great explanation
@amritraj7426
@amritraj7426 3 жыл бұрын
Level Order Traversal (C++) class Solution { public: int maxDepth(TreeNode* root) { if(!root) return 0; int level=0; queue q; q.push(root); while(!q.empty()){ int n=q.size(); for(int i=0; ileft) q.push(node->left); if(node->right) q.push(node->right); } level++; } return level; } };
@sumitkanth5349
@sumitkanth5349 2 жыл бұрын
Can you provide recursive code to solve the problem plz
@nidhinishad7801
@nidhinishad7801 Жыл бұрын
level order int bfs(struct node *head){ int l=0,r=0,maxi=INT_MIN; queue q; q.push(head); while(!q.empty()){ node *temp = q.front(); q.pop(); if(temp->left!=NULL){ q.push(temp->left); l++; } if(temp->right!=NULL){ q.push(temp->right); r++; } maxi = max(l,r); } return maxi; }
@psuedocoder7781
@psuedocoder7781 3 жыл бұрын
public static int maxDepth(TreeNode root){ int left = 1, right= 1; if(!(root.left == null)){ left = 1+maxDepth(root.left); } if(!(root.right == null)){ right = 1+maxDepth(root.right); } return Integer.max(left, right); }
@mriduljain1981
@mriduljain1981 Жыл бұрын
completed lecrure 14 of Tree playlist.
@PRASHANTSINGH-yq9hh
@PRASHANTSINGH-yq9hh Жыл бұрын
int maxDepth(TreeNode* root) { int height=0; if(root==NULL) return height; queue q; q.push(root); while(!q.empty()){ int sz=q.size(); ++height; for(int i=0;ileft!=NULL) q.push(root->left); if(root->right!=NULL) q.push(root->right); } } return height; }
@alesblaze4745
@alesblaze4745 2 жыл бұрын
this is going, nice bro!
@kshitij618
@kshitij618 Жыл бұрын
Just do Level order and return the length of the list+1.
@vakhariyajay2224
@vakhariyajay2224 Жыл бұрын
Thank you very much.
@AmanYadav-jf1yy
@AmanYadav-jf1yy Жыл бұрын
// Maximum Depth using Level order traversal . int maxDepth(TreeNode* root) { if(root==nullptr) return 0; queue q; q.push(root); int ans=0; while(!q.empty()) { ans++; int size=q.size(); for(int i=0;ileft) q.push(temp->left); if(temp->right) q.push(temp->right); } } return ans; }
@priyanshubharti5198
@priyanshubharti5198 3 жыл бұрын
understood bhaiya ...🔥🔥
L15. Check for Balanced Binary Tree | C++ | Java
12:30
take U forward
Рет қаралды 371 М.
L8. Level Order Traversal of Binary Tree | BFS | C++ | Java
8:57
take U forward
Рет қаралды 431 М.
Chain Game Strong ⛓️
00:21
Anwar Jibawi
Рет қаралды 41 МЛН
My scorpion was taken away from me 😢
00:55
TyphoonFast 5
Рет қаралды 2,7 МЛН
My Brain after 569 Leetcode Problems
7:50
NeetCode
Рет қаралды 2,7 МЛН
I Redesigned the ENTIRE YouTube UI from Scratch
19:10
Juxtopposed
Рет қаралды 912 М.
Height of a Binary Tree / Maximum depth of a binary tree Algorithm [REVISITED]
16:50
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 120 М.
When the #1 Shen LIMIT-TESTS... *Legendary in 11 Minutes*
19:47
8 patterns to solve 80% Leetcode problems
7:30
Sahil & Sarra
Рет қаралды 473 М.
Understanding B-Trees: The Data Structure Behind Modern Databases
12:39