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

  Рет қаралды 325,253

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
@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
@Reyna-yj6vo
@Reyna-yj6vo 4 ай бұрын
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); }
@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 10 ай бұрын
@@raghavchawla1658 same question
@SohelDarwajkar
@SohelDarwajkar 9 ай бұрын
​@@nitpBlogsFollow Aditya Verma's Recursion Playlist and until the end of the playlist The recursion in trees will be like a cakewalk ..
@SaiSumanthKovuru
@SaiSumanthKovuru 10 ай бұрын
Greatest series ever seen on Trees
@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
@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 😂
@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 ; } }
@sheetalbhattamisra2000
@sheetalbhattamisra2000 Жыл бұрын
Tree has not been that easy before your video ....thanks so much for a2z DS ....the best video on KZbin
@kushalchakraborty6970
@kushalchakraborty6970 2 жыл бұрын
For level order just keep a cnt variable and do ++ within the loop
@amanpreetsinghbawa1600
@amanpreetsinghbawa1600 22 күн бұрын
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 16 күн бұрын
Damn
@Kartik-s8r
@Kartik-s8r 5 ай бұрын
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(); } };
@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; }
@josephhsia
@josephhsia 9 ай бұрын
What an elegantly simple solution to finding a binary tree in 5 lines of code...
@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
@zee_desai
@zee_desai 5 ай бұрын
Python one liner: def height(node): return 0 if not node else max(height(node.left), height(node.right) )+ 1
@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 Жыл бұрын
Can you provide recursive code to solve the problem plz
@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;
@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
@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; }
@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
@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..
@vardhamanbhandari5644
@vardhamanbhandari5644 Жыл бұрын
u'r teching method is amazing striver, Hands off to your efforts🙌🙌🙌
@TheWierdVibe
@TheWierdVibe 2 жыл бұрын
the best series on KZbin!
@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; }
@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;
@pratyushtripathi1728
@pratyushtripathi1728 7 ай бұрын
Understood 😊
@faltubaccha.2498
@faltubaccha.2498 4 ай бұрын
Striver man!, thank you for helping me increase my intrest is DS Algo ❤
@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 ```
@abhijitbiradar
@abhijitbiradar 2 жыл бұрын
Very beautifully explained. Many Thanks
@navyasreepinjala1582
@navyasreepinjala1582 3 ай бұрын
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
@bhavkushwaha
@bhavkushwaha 7 ай бұрын
Thankyou Striver, Understood!
@nawabkhan4916
@nawabkhan4916 2 жыл бұрын
great work, and have lots of sponsor ad so that you can provide great videos.
@DhananjayKumar-vn5tc
@DhananjayKumar-vn5tc 2 жыл бұрын
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--; } }
@guneeshvats46
@guneeshvats46 4 ай бұрын
amazing explanation although I had to watch it 3 times but still it was to the point
@akhileshgoswami7699
@akhileshgoswami7699 3 жыл бұрын
best video on maximum Depth in binary tree im commenting before watching coz i Know you make best
@prabhakaran5542
@prabhakaran5542 4 ай бұрын
Understood ❤
@per.seus._
@per.seus._ Жыл бұрын
understood dada❤
@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
@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
@easycode3189
@easycode3189 2 жыл бұрын
Simple Explanation || Understud 100% || Thanks alot
@sumitkanth5349
@sumitkanth5349 Жыл бұрын
Can you provide recursive code to solve the problem plz
@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
@ganeshjaggineni4097
@ganeshjaggineni4097 4 ай бұрын
NICE SUPER EXCELLENT MOTIVATED
@rahatsshowcase8614
@rahatsshowcase8614 2 жыл бұрын
The work recursion does is huge and the code is very very cute;
@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 Ай бұрын
i also have same doubt
@Miraculousbuddy-gh7me
@Miraculousbuddy-gh7me 3 ай бұрын
Kindly post the practice problems as well , Sir .
@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
@architmishra0057
@architmishra0057 Ай бұрын
If root is null then return -1 not 0 that's why it gives height as 4 not 3 0:53 .
@Ramu9119
@Ramu9119 11 ай бұрын
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; }
@ankushmallick6968
@ankushmallick6968 3 ай бұрын
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(); } };
@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 2 ай бұрын
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
@sniperboy2314
@sniperboy2314 2 ай бұрын
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; }
@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
@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; } };
@atulk9122
@atulk9122 3 жыл бұрын
again cleared many doubts in one shot
@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
@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 8 ай бұрын
/* 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
@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; }
@psuedocoder7781
@psuedocoder7781 2 жыл бұрын
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); }
@ranupandey8490
@ranupandey8490 9 ай бұрын
Done sir- level order.
@nextnotification9857
@nextnotification9857 8 ай бұрын
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; }
@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(); } };
@sanchitkadwe90
@sanchitkadwe90 2 жыл бұрын
Creating a variable and passing it by reference and upadating the value accordingly. Is this a good solution ??
@mriduljain1981
@mriduljain1981 Жыл бұрын
completed lecrure 14 of Tree playlist.
@NishantKumar-fq5zr
@NishantKumar-fq5zr 10 ай бұрын
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; }
@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; }
@snippetsandsolutions
@snippetsandsolutions Жыл бұрын
Height of binary tree is based on edges not on nodes right ? This solution will return height as 1 even the tree only have root node. So I guess we should return -1 if the root == null
@kshitij618
@kshitij618 Жыл бұрын
Just do Level order and return the length of the list+1.
@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;
@DeadPoolx1712
@DeadPoolx1712 Ай бұрын
UNDERSTOOD;
@apmotivationakashparmar722
@apmotivationakashparmar722 Ай бұрын
Thank you So much.
@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; }
@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; } };
@viralpw5846
@viralpw5846 3 ай бұрын
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; } };
@a12gaming61
@a12gaming61 Күн бұрын
Thanks man🙌
@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 Жыл бұрын
Can you provide recursive code to solve the problem plz
@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; } };
@sarangkumarsingh7901
@sarangkumarsingh7901 3 ай бұрын
Awesome..........
@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; }
@nimisharawat9949
@nimisharawat9949 5 ай бұрын
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
@sathwikavontela885
@sathwikavontela885 3 ай бұрын
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.
@AdityaSinghMandloi
@AdityaSinghMandloi Ай бұрын
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; } };
@AI_for_funn
@AI_for_funn 3 жыл бұрын
great video , out of world level explanation
@keerthireddy8074
@keerthireddy8074 Жыл бұрын
Level Order Traversal in JAVA : class Solution { int height(Node node) { Queue q = new LinkedList(); int count =0; if (node == null) return count; q.offer(node); while (!q.isEmpty()){ int levelNum = q.size(); for (int i=0; i
@UECAshutoshKumar
@UECAshutoshKumar Жыл бұрын
Thank you sir
@sparshsharma3150
@sparshsharma3150 3 жыл бұрын
Amazingly explained! Waiting for more complex problems on trees. Striver bhaiya op!!
@cinime
@cinime 2 жыл бұрын
Understood! So amazing explanation as always, thank you very much!!
@akshatnigam7835
@akshatnigam7835 Жыл бұрын
just return the size of arraylist in level order traversal to have max depth!
@sakshitiwari8700
@sakshitiwari8700 3 жыл бұрын
My approach using level order traversal : int maxDepth(TreeNode* root) { if(root==NULL) return 0; queue q; q.push({root, 1}); int depth; while(!q.empty()){ TreeNode*curr=(q.front()).first; if(curr->left) q.push({curr->left, (q.front()).second+1}); if(curr->right) q.push({curr->right, (q.front()).second+1}); if(q.size()==1) depth = (q.front()).second; q.pop(); } return depth; } Bhaiya plz tell if this approach is efficient or not.
@rajeshsingh-mv7zn
@rajeshsingh-mv7zn 2 жыл бұрын
I have similar solution using recursion. Do you think this is efficient because we are traversing all nodes like here. var maxDepth = function(root) { let max = 0; if(root == null) return 0; function helper(root,level){ if(root == null) return; max = Math.max(max,level); helper(root.left,level+1); helper(root.right,level+1); } helper(root,1); return max; };
@sakshitiwari8700
@sakshitiwari8700 2 жыл бұрын
@@rajeshsingh-mv7zn See we have to traverse all the nodes for knowing the height of the tree.
@kaustubhwaghavkar9079
@kaustubhwaghavkar9079 2 жыл бұрын
Thanks for this video. Very helpful. So basically max depth is indirectly finding the height of the binary tree, right?
@csea_37_shayoribhowmick53
@csea_37_shayoribhowmick53 Жыл бұрын
Thank you so much ❤
@Shivi32590
@Shivi32590 4 ай бұрын
thank you
@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; } };
@artitech6668
@artitech6668 2 жыл бұрын
Great explanation
@Ergoswami
@Ergoswami 7 ай бұрын
Completed!
@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); };
L15. Check for Balanced Binary Tree | C++ | Java
12:30
take U forward
Рет қаралды 357 М.
8 patterns to solve 80% Leetcode problems
7:30
Sahil & Sarra
Рет қаралды 438 М.
I thought one thing and the truth is something else 😂
00:34
عائلة ابو رعد Abo Raad family
Рет қаралды 5 МЛН
When u fight over the armrest
00:41
Adam W
Рет қаралды 31 МЛН
L16. Diameter of Binary Tree | C++ | Java
13:47
take U forward
Рет қаралды 378 М.
Height of a Binary Tree / Maximum depth of a binary tree Algorithm [REVISITED]
16:50
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 119 М.
Top 7 Algorithms for Coding Interviews Explained SIMPLY
21:22
Codebagel
Рет қаралды 442 М.
I gave 127 interviews. Top 5 Algorithms they asked me.
8:36
Sahil & Sarra
Рет қаралды 673 М.
Premature Optimization
12:39
CodeAesthetic
Рет қаралды 834 М.
Beginners Should Think Differently When Writing Golang
11:35
Anthony GG
Рет қаралды 123 М.
31 nooby C++ habits you need to ditch
16:18
mCoding
Рет қаралды 825 М.
I thought one thing and the truth is something else 😂
00:34
عائلة ابو رعد Abo Raad family
Рет қаралды 5 МЛН