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

Example 1:
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.

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


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


Note:

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

二叉树剪枝。

给定二叉树根结点 root ,此外树的每个结点的值要么是 0,要么是 1。

返回移除了所有不包含 1 的子树的原二叉树。

( 节点 X 的子树为 X 本身,以及所有 X 的后代。)

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-pruning
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是后序遍历。对于每一个节点值 node.val,如果他没有左右孩子或者他的左右孩子的节点值都是 0 的话,就把他剪除(往上返回 null)。可以和1325题放在一起做,两者几乎是同一道题。

时间O(n)

空间O(n)

Java实现

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode() {}
 8  *     TreeNode(int val) { this.val = val; }
 9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 class Solution {
17     public TreeNode pruneTree(TreeNode root) {
18         // corner case
19         if (root == null) {
20             return null;
21         }
22         root.left = pruneTree(root.left);
23         root.right = pruneTree(root.right);
24         if (root.left == null && root.right == null && root.val == 0) {
25             return null;
26         }
27         return root;
28     }
29 }

 

相关题目

814. Binary Tree Pruning

1325. Delete Leaves With a Given Value

LeetCode 题目总结

posted @ 2020-12-02 02:23  CNoodle  阅读(61)  评论(0编辑  收藏  举报