Leetcode学习笔记:#814. 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.)
实现:
public TreeNode pruneTree(TreeNode root){
if(root == null)
return null;
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
if(root.left == null && root.right == null && root.val == 0) return null;
return root;
思路:
前序遍历二叉树。只有是节点值为0且没有1作为子节点的情况下才删除该节点,从下到上求出二叉树即可。