Microsoft's Most Asked Question 2021 - Count Good Nodes in a Binary Tree - Leetcode 1448 - Python

  Рет қаралды 80,096

NeetCode

NeetCode

Күн бұрын

🚀 neetcode.io/ - A better way to prepare for Coding Interviews
🐦 Twitter: / neetcode1
🥷 Discord: / discord
🐮 Support the channel: / neetcode
⭐ BLIND-75 PLAYLIST: • Two Sum - Leetcode 1 -...
💡 CODING SOLUTIONS: • Coding Interview Solut...
💡 DYNAMIC PROGRAMMING PLAYLIST: • House Robber - Leetco...
🌲 TREE PLAYLIST: • Invert Binary Tree - D...
💡 GRAPH PLAYLIST: • Course Schedule - Grap...
💡 BACKTRACKING PLAYLIST: • Word Search - Backtrac...
💡 LINKED LIST PLAYLIST: • Reverse Linked List - ...
💡 BINARY SEARCH PLAYLIST: • Binary Search
Problem Link: neetcode.io/problems/count-go...
0:00 - Read the problem
1:40 - Drawing Explanation
5:21 - Coding Explanation
leetcode 1448
This question was identified as a microsoft interview question from here: github.com/xizhengszhang/Leet...
#binary #tree #python
Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.

Пікірлер: 54
@NeetCode
@NeetCode 3 жыл бұрын
🌲 TREE PLAYLIST: kzbin.info/www/bejne/hZ-2n2WOerZng7s
@surepasu
@surepasu 3 жыл бұрын
I cannot thank you enough for your videos . They are crisp and easy to follow. For me , your channel become the one stop for all my learning .Using Python simplified even further.
@kuoyulu6714
@kuoyulu6714 10 ай бұрын
So simple and easy the way you did it! I was using a Set and adding each good node to my set, but counting good node is so much easier the way you did it. Thanks for the vid as always!
@chenjus
@chenjus 3 жыл бұрын
Alternative using nonlocal good = 0 def dfs(node, parent): nonlocal good if not node: return if node.val >= parent: good += 1 max_ = max(parent, node.val) dfs(node.left, max_) dfs(node.right, max_) dfs(root, root.val) return good
@ladydimitrescu1155
@ladydimitrescu1155 Жыл бұрын
this is pretty good, thanks
@stylisgames
@stylisgames Ай бұрын
I actually got this one without looking at any hints! 🙌Doing all of the previous BST problems beforehand helped greatly.
@The6thProgrammer
@The6thProgrammer 9 ай бұрын
Can be done easily with BFS as well. There is also no rule against updating the node values, so I used BFS and every time I added a new node to the queue I updated that nodes value if it was < root->val
@ziontan4402
@ziontan4402 3 жыл бұрын
Thank you for your video! Well-explained and it's amazing!
@symbol767
@symbol767 2 жыл бұрын
Right after you explained the problem in the first 3min I understood it immediately and realized I needed to just keep track of the max value in the current path. Looking at your solution, seems I figured it out correctly, thank you man. Liked
@rajdeepchakraborty7961
@rajdeepchakraborty7961 12 күн бұрын
How to track max value
@rajdeepchakraborty7961
@rajdeepchakraborty7961 12 күн бұрын
btw, where are you from?
@piyusharyaprakash4365
@piyusharyaprakash4365 11 ай бұрын
I did the same, but I used extraspace. Used a array to store the path and update count only if the last element of the array is the max element. It pretty much runs the same! class Solution: def goodNodes(self, root: TreeNode) -> int: count = 0 def dfs(root,res): nonlocal count if not root: return res res.append(root.val) if max(res) == res[-1]: count += 1 dfs(root.left,res) dfs(root.right,res) res.pop() return res dfs(root,[]) return count
@neel1901
@neel1901 4 ай бұрын
i performed a level order traversal and was pushing the node's value if it was greater than max value else i was just pushing the max value for both subtrees(if current node value was greater than max) i just incremented the counter
@arpanbanejee5143
@arpanbanejee5143 2 жыл бұрын
Nice recursive solution, but this can be more intuitive- kind of similar to LCS prob class Solution { public int goodNodes(TreeNode root) { if (root == null) return 0; return helper(root,root.val); } public static int helper(TreeNode root, int max){ if (root == null) return 0; if (root.val >= max){ return 1 + helper(root.left,Math.max(root.val,max)) + helper(root.right,Math.max(root.val,max)); } else { return helper(root.left,max) + helper(root.right,max); } } }
@davidmwangi4312
@davidmwangi4312 2 жыл бұрын
Great solution,
@abhinaygupta
@abhinaygupta 3 жыл бұрын
Great explanation. Caught the idea in between just by your explanation. And congratulations on 10 K
@TaiChiSWAG
@TaiChiSWAG Жыл бұрын
Its 330K now
@hrushikway
@hrushikway 9 ай бұрын
It’s almost 600K now 🎉
@IK-xk7ex
@IK-xk7ex Жыл бұрын
The another one problem I could come up with myself. But as always I watch your videos to find more smart solution
@shubham900100
@shubham900100 Жыл бұрын
I always feel like if you use nonlocal in helper functions, it'll make your life a ton easier... # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def goodNodes(self, root: TreeNode) -> int: cnt=0 def helper(root,max_val): nonlocal cnt if not root: return max_val=max(max_val,root.val) if root.val>=max_val: cnt+=1 helper(root.left,max_val) helper(root.right,max_val) helper(root,root.val) return cnt
@malakggh
@malakggh Жыл бұрын
yea and you can also do the same using self: self.cnt = 0 then every where inside the helper function use self.cnt = ...
@aliciama1745
@aliciama1745 Жыл бұрын
Hi, NeetCode, Just curious, was your website created by using html, css and js, or you created by using website builder? If you build it by using html etc, how long will it take you to finish this? thank you
@NeetCode
@NeetCode Жыл бұрын
Yeah i built it from scratch, i talk about it in this video: kzbin.info/www/bejne/aniYpWR-rK2EepY
@shashankbarole
@shashankbarole 3 жыл бұрын
Congratulations on 10k subscribers!!
@NeetCode
@NeetCode 3 жыл бұрын
Thanks!
@leeroymlg4692
@leeroymlg4692 Жыл бұрын
a year later and he's at almost 300k subscribers
@natnaelzewdu4289
@natnaelzewdu4289 3 ай бұрын
and now he is at 699K 😂
@hemantkapoor6777
@hemantkapoor6777 Жыл бұрын
wow i am speechless, crazy ! You a god!
@muzaffartursunov324
@muzaffartursunov324 7 ай бұрын
good job bro!
@tarunsethi6041
@tarunsethi6041 7 ай бұрын
If you add 'res' as a parameter of your dfs function, only one stack frame will be used irrespective of how many times dfs is called recursively because of compiler optimization called "tail recursion"
@ranvirchhina5179
@ranvirchhina5179 7 ай бұрын
python doesn't optimize tail recursion
@edwardteach2
@edwardteach2 2 жыл бұрын
U a God
@saketsingh1055
@saketsingh1055 2 жыл бұрын
i am yelling too because its hard to do tree questions with recursion🙃🙃
@yoyo8293
@yoyo8293 3 жыл бұрын
Congrats on 10K !! can you share from where you get the latest questions asked in FAANG
@huangCAnerd
@huangCAnerd 2 жыл бұрын
Why is the space complexity O(logN) or the height of the tree?
@clashwidzack7298
@clashwidzack7298 Жыл бұрын
because in worst case our function can call max number of function calls that are equal to the height of three. Now at a time tree can grow in only one direction(path) and that path might have max no of nodes among all other paths and since our function has to cover those nodes with the help of function call it will call the those number of nodes
@mostinho7
@mostinho7 Жыл бұрын
Done Thanks Similar approach to verifying binary tree, doing a “pre-order- traversal and passing max encountered node from root until now to each recursive call
@nikhildinesan5259
@nikhildinesan5259 3 жыл бұрын
Kudos on 10k !!!❤️❤️
@chiamakabrowneyes
@chiamakabrowneyes 2 жыл бұрын
he is on 103K subscribers rn !
@farazahmed7
@farazahmed7 2 жыл бұрын
@@chiamakabrowneyes 155k now. He's growing like nuts. Fully deserved
@MrACrazyHobo
@MrACrazyHobo 3 жыл бұрын
I kind of wanted to hear what your neighbors were yelling about lol
@bernardoramirez1759
@bernardoramirez1759 Күн бұрын
“No one solves that under 30 mins”
@HyunBinKim-yo9fx
@HyunBinKim-yo9fx 2 жыл бұрын
Does anyone know why the space complexity is logarithmic?
@chaoluncai4300
@chaoluncai4300 Жыл бұрын
assume you haven't figure out yet lol, since we are doing dfs, and the max no. of method call frames that can exist on stack is the max(height of tree), which is log(Node)
@JiaTanchun
@JiaTanchun Жыл бұрын
RecursionError: maximum recursion depth exceeded in comparison
@kanishkameta5377
@kanishkameta5377 27 күн бұрын
int helper(TreeNode* root, int prev){ if(root==NULL) return 0; if(root->val>=prev) return 1+helper(root->right,root->val)+helper(root->left,root->val); else return helper(root->right,prev)+helper(root->left,prev); } int goodNodes(TreeNode* root) { return helper(root,INT_MIN); } C++ implementation
@jonaskhanwald566
@jonaskhanwald566 3 жыл бұрын
same code but: Runtime: 272 ms, faster than 37.86% of Python3 online submissions for Count Good Nodes in Binary Tree. Memory Usage: 33.6 MB, less than 13.16% of Python3 online submissions for Count Good Nodes in Binary Tree.
@yijingzhang3191
@yijingzhang3191 2 жыл бұрын
why it is so easy to you😭
@ningzedai9052
@ningzedai9052 Жыл бұрын
I think this question should be labeled as "Easy" instead of "Medium" .
@JohnTosun
@JohnTosun Жыл бұрын
It is medium because you can do different approaches with it. If you can do brute force and pass, it could be easy
@NihongoWakannai
@NihongoWakannai Жыл бұрын
Yeah all you have to do to pass it is basically just traverse a tree. There are easy questions which are more complex than this
@jonaskhanwald566
@jonaskhanwald566 3 жыл бұрын
Do both iterative and recursive approaches in future
@CEOofTheHood
@CEOofTheHood 3 жыл бұрын
how about Please Do both iterative and recursive approaches in future. Hes doing you a favor.
@rommeltito123
@rommeltito123 2 жыл бұрын
Umm no ...I am not checking interviewing.io ...... I find neetcode better!
Flatten Binary Tree to Linked List - Leetcode 114 - Python
14:27
How I Failed the Google Coding Interview (and lessons I learned)
14:24
Why Is He Unhappy…?
00:26
Alan Chikin Chow
Рет қаралды 67 МЛН
ВОДА В СОЛО
00:20
⚡️КАН АНДРЕЙ⚡️
Рет қаралды 35 МЛН
Balanced Binary Tree - Leetcode 110 - Python
13:11
NeetCode
Рет қаралды 230 М.
I gave 127 interviews. Top 5 Algorithms they asked me.
8:36
Sahil & Sarra
Рет қаралды 633 М.
Why Starbucks Is Struggling
12:06
CNBC
Рет қаралды 465 М.
The moment we stopped understanding AI [AlexNet]
17:38
Welch Labs
Рет қаралды 852 М.
Why The Olympics Banned Nike
9:57
Athletic Interest
Рет қаралды 274 М.
8 patterns to solve 80% Leetcode problems
7:30
Sahil & Sarra
Рет қаралды 288 М.
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 400 М.
5 Math Skills Every Programmer Needs
9:08
Sahil & Sarra
Рет қаралды 1 МЛН
Как удвоить напряжение? #электроника #умножитель
1:00
Hi Dev! – Электроника
Рет қаралды 1,1 МЛН
ноутбуки от 7.900 в тг laptopshoptop
0:14
Ноутбуковая лавка
Рет қаралды 3,5 МЛН
Опасность фирменной зарядки Apple
0:57
SuperCrastan
Рет қаралды 12 МЛН
Это iPhone 16
0:52
Wylsacom
Рет қаралды 522 М.