LeetCode 剑指 Offer II 047. 二叉树剪枝
题目描述
给定一个二叉树 根节点 root ,树的每个节点的值要么是 0,要么是 1。请剪除该二叉树中所有节点的值为 0 的子树。
节点 node 的子树为 node 本身,以及所有 node 的后代。
示例 1:
输入: [1,null,0,0,1]
输出: [1,null,0,null,1]
LeetCode 剑指 Offer II 047. 二叉树剪枝
提示:
一、解题关键词
二、解题报告
1.思路分析
2.时间复杂度
3.代码示例
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode pruneTree(TreeNode root) {
//本质为树的遍历
if(null == root) return root;
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
if(root.val == 0 && root.left == null && root.right == null){
root = null;
}
return root;
}
}
2.知识点
树的遍历
1、递归遍历
2、非递归遍历