其他分享
首页 > 其他分享> > [LeetCode] 814. Binary Tree Pruning

[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:

二叉树剪枝。

题意是给一棵二叉树,node.val只有0和1两种情况,请你返回这棵树但是请把所有不包含1的子树去掉。

思路是后序遍历。对于每一个节点值node.val,如果他没有左右孩子或者他的左右孩子的节点值都是0的话,就把他剪除(往上返回null)。

时间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 }

 

LeetCode 题目总结

标签:node,Binary,right,TreeNode,val,root,null,814,LeetCode
来源: https://www.cnblogs.com/cnoodle/p/14071731.html