bool res=true; int f(Node* root){ if(!root)return 0; int l=f(root->left); int r=f(root->right); if(!root->left && !root->right)return root->data; if(root->data!=l+r)res=false; return l+r+root->data; } bool isSumTree(Node* root) { res=true; f(root); return res; }
@iztebah81182 жыл бұрын
We can return if (a+b != root->data). As we already found the solution no need to further iterate.
@dhruv20143 жыл бұрын
Nice code and easy to understand 🔥🔥
@divyanshuchaudhari54163 жыл бұрын
if (f==0):return 0 is not required.In every recursive call it is checking this condition even before node condition is checked.So,no use. Otherwise great explanation bro..Keep going.
@rajatmaheshwari46563 жыл бұрын
also f = 1 in bool not req, just a global var is sufficient
@rogeliojaylon44773 жыл бұрын
So Nice 💘💘💘💘💘💘
@nirajdas13313 жыл бұрын
+1 for elegant solution
@hiteshusingh85713 жыл бұрын
Good Explanation!
@sandipan_c Жыл бұрын
There's no need to continue further if we see that, sum of leaves and its root is not equal. Python code is attached below. def recur(node): nonlocal flag if node is None: return 0 if node.left is None and node.right is None: return node.data else: sl = recur(node.left) sr = recur(node.right) if sl == -1 or sr == -1: return -1 if sl+sr != node.data: return -1 return sl + sr + node.data p = recur(root) return 0 if p == -1 else 1
@kunalverma97773 жыл бұрын
brute->better->optimal only discussing code is not helpful at all
@akashchanabasanavar3031 Жыл бұрын
Is this code pass the case???
@ankur420ify Жыл бұрын
solution not working for all corner cases.
@sainisaab6842 жыл бұрын
how to detrermine stack of tree is used or not!!???
@BACSShaileshShettar4 ай бұрын
the code provided in video is wrong. below is correct code. class Solution { boolean isSumTree(Node root) { boolean[] ans=new boolean[1]; ans[0]=true; int res=recurse(root,ans); return ans[0]; } static int recurse(Node root,boolean[] ans) { if (root==null) return 0; int left=recurse(root.left,ans); int right=recurse(root.right,ans); int sum=left+right; if (sum!=root.data && sum!=0) ans[0]=false; root.data+=sum; //System.out.println(root.data); return root.data; } }
@mastersk74403 жыл бұрын
Sare topic ka basic ka bad question karwaya
@aishwaryajaiswal47203 жыл бұрын
I wrote the same code and it's not working
@akshaytak77752 жыл бұрын
Maybe you globally initialized f =1, due to which your function is always returning true.
@Viralmems_xyz Жыл бұрын
bakbass explain
@mastersk74403 жыл бұрын
Bhai basic se karwoa yar
@luffyy80843 жыл бұрын
62 16 15 N 8 4 7 N 8 4 for this input gfg is saying output is wrong..can anyone help why this code doesnt work for this input?
@akashjaiswal64783 жыл бұрын
check after sometime it will give correct solution