Binary Tree Pruning

We are given the head node root of a binary tree, where additionally every node's value is either a 0 or a 1.

Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.

(Recall that the subtree of a node X is X, plus every node that is a descendant of X.)

Example:

Input: [1,null,0,0,1]
Output: [1,null,0,null,1]

Approach:

C++

#include <bits/stdc++.h>
using namespace std;
//struct for treenode
struct TreeNode
{
    int data;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int data)
    {
        this->data = data;
        this->left = NULL;
        this->right = NULL;
    }
};
void printTree(TreeNode *root)
{
    queue<TreeNode *> q;
    q.push(root);
    vector<stringvec;
    while (!q.empty())
    {
        root = q.front();
        q.pop();
        if (root == NULL)
            vec.push_back("null");
        else
            vec.push_back(to_string(root->data));
        if (root != NULL)
        {
            q.push(root->left);
            q.push(root->right);
        }
    }
    int j = vec.size() - 1;
    while (j > 0 && vec[j] == "null")
        j--;
    vec.resize(j);
    for (int i = 0i < ji++)
        cout << vec[i] << ",";
    cout << vec[j];
}
TreeNode *pruneTree(TreeNode *root)
{
    if (root == NULL)
    {
        return NULL;
    }

    root->left = pruneTree(root->left);
    root->right = pruneTree(root->right);
    if (!root->left && !root->right && root->data == 0)
        return NULL;
    else
        return root;
}

int main()
{
    TreeNode *root = new TreeNode(1);
    root->right = new TreeNode(0);
    root->right->left = new TreeNode(0);
    root->right->right = new TreeNode(1);

    TreeNode *res = pruneTree(root);
    cout << "[";
    printTree(res);
    cout << "]";
    return 0;
}


No comments:

Post a Comment