欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

814. Binary Tree Pruning

程序员文章站 2022-04-25 10:41:11
...

Problem

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.)

Note:

The binary tree will have at most 100 nodes.
The value of each node will only be 0 or 1.

Example1

Input: [1,null,0,0,1]
Output: [1,null,0,null,1]
Explanation:
Only the red nodes satisfy the property “every subtree not containing a 1”.
The diagram on the right represents the answer.
814. Binary Tree Pruning

Example2

Input: [1,0,1,0,0,0,1]
Output: [1,null,1,null,1]
814. Binary Tree Pruning

Example3

Input: [1,1,0,1,1,0,1,0]
Output: [1,1,0,1,1,null,1]
814. Binary Tree Pruning

Solution

后序遍历,递归。
在每个节点处,判断以它为根的树是否包含1。如果不包含,就将这棵树删掉。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* pruneTree(TreeNode* root) {
        if(!root)
            return root;
        root->left = pruneTree(root->left);
        root->right = pruneTree(root->right);

        if(!isTreeContainsOne(root))
        {
            deleteTreeFromCurrentNode(root);
            return NULL;
        }

        return root;

    }

    bool isTreeContainsOne(TreeNode *root)
    {
        if(!root)
            return false;
        if(root->val ==1)
            return true;
        return isTreeContainsOne(root->left) || isTreeContainsOne(root->right);
    }

    void deleteTreeFromCurrentNode(TreeNode *root)
    {
        if(!root)
            return;
        deleteTreeFromCurrentNode(root->left);
        deleteTreeFromCurrentNode(root->right);

        root->left = NULL;;
        root->right = NULL;
        delete root;
    }
};