This was my attempt/solution before watching this. It's so cool being able to do it myself and see a completely different way of coding this up class Solution { private int dfs(TreeNode root, char direction) { if (root == null) return 0; if (root.left == null && root.right == null) { // System.out.println(" Found leaf: " + root.val); if (direction == 'L') { return root.val; } else { return 0; } } return dfs(root.left, 'L') + dfs(root.right, 'R'); } public int sumOfLeftLeaves(TreeNode root) { return dfs(root.left, 'L') + dfs(root.right, 'R'); } }
@aimeewildstone46023 жыл бұрын
I really appreciate you going over recursive and iterative solutions along with clear explanations. I’m looking forward to more of your videos!
@AlgosWithMichael3 жыл бұрын
More to come!
@eldavimost2 жыл бұрын
Great explanation! What program do you use to create the graphics and paint on it?
@B-Billy3 жыл бұрын
Thank you... clear and detailed explanation
@AlgosWithMichael3 жыл бұрын
Glad it was helpful!
@saulgoodman6710 Жыл бұрын
if you add the isleafnode() check for the right nodes before adding to the queue it would me more optimal right? because if right node is leaf node we dont need to add it to the queue. Let me know ur views
@abhinavghosh7254 жыл бұрын
hey man!good video! one question ,why cant i use global variable, we are setting sum=0 in every recursion call why cant we do like this: class Solution { int sum=0; public int sumOfLeftLeaves(TreeNode root) { if(root==null)return 0; // int sum=0; if(root.left!=null) { if(root.left.left==null && root.left.right==null) { sum+=root.left.val; } else { sum+=sumOfLeftLeaves(root.left); } } sum+=sumOfLeftLeaves(root.right); return sum; } } i have been having problems with tree questions from a very long time! can you please make a video explaining how actually recursion works in a tree! its a request man ! please do a specific video for that! thanks!
@AlgosWithMichael4 жыл бұрын
Hey! Thanks for the question. The reason why we can't set a global variable in the recursive approach is because we are building the sum bottom-up. If we have a global variable, the line `sum += root.left.val` will effect recursive calls below it if that makes sense. With the following input `[3,9,20,null,null,15,7]`, your code outputs `57` when it should be outputting `24`. Hope that makes sense and thank you so much watching!
@stardriver86603 жыл бұрын
class Solution { public int sumOfLeftLeaves(TreeNode root) { return helper(root,"root"); } public int helper(TreeNode root,String mark){ if(root == null)return 0; if(root.left == null && root.right == null){ if(mark.equals("left"))return root.val; } return helper(root.left,"left") + helper(root.right,"right"); } } How do you like my solution?