814. Binary Tree Pruning
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.
Example2
Input: [1,0,1,0,0,0,1]
Output: [1,null,1,null,1]
Example3
Input: [1,1,0,1,1,0,1,0]
Output: [1,1,0,1,1,null,1]
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;
}
};
上一篇: leetcode 344——翻转字符串
下一篇: 设计模式读书笔记-----状态模式
推荐阅读
-
leetcode笔记:Invert Binary Tree
-
Convert Sorted Array to Binary Search Tree
-
minimum-depth-of-binary-tree
-
cf438E. The Child and Binary Tree(生成函数 多项式开根 多项式求逆)
-
【leetcode】-700. Search in a Binary Search Tree 查找二叉搜索树
-
Leetcode——108. Convert Sorted Array to Binary Search Tree
-
Leetcode 108. Convert Sorted Array to Binary Search Tree
-
21天刷题计划之17.1—maximum-depth-of-binary-tree(二叉树的最大深度)(Java语言描述)
-
21天刷题计划之18.1—balanced-binary-tree(平衡二叉树)(Java语言描述)
-
PAT甲级 1151 LCA in a Binary Tree (30分) 最近公共祖先