Burn a Tree

 https://www.interviewbit.com/problems/burn-a-tree/


 int dfs (TreeNode *A, int &h, int &ans, int B)
{
if (!A)
return 0;

int hr = 0, hl = 0;

bool leftfire = false, rightfire = false;

leftfire = dfs (A->left, hl, ans, B);
rightfire = dfs (A->right, hr, ans, B);

if (!leftfire && !rightfire)
    h = max (hr, hl) + 1;
else if (leftfire)
    h = hl+1;
else h = hr+1;

if (B == A->val || leftfire || rightfire)
{
    ans = max (ans, hr + hl + 1);
    return 1;
}
return 0;

}
int Solution::solve(TreeNode* A, int B) {
    int ans = 0, h = 0;
    dfs (A, h, ans, B);
    return ans - 1;
}


 

Comments

Popular posts from this blog

Perfect Peak of Array

Is Rectangle?

Sort array with squares!