本文共 1138 字,大约阅读时间需要 3 分钟。
给定二叉树根结点 root ,此外树的每个结点的值要么是 0,要么是 1。
返回移除了所有不包含 1 的子树的原二叉树。
( 节点 X 的子树为 X 本身,以及所有 X 的后代。)
示例1:
输入: [1,null,0,0,1] 输出: [1,null,0,null,1]/** * 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) { //移除子树全部都是 0 的树 if(root == null) return null; return new Tree(root).get(); } static class Tree{ TreeNode root; Tree(TreeNode root) { this.root = root;} TreeNode get() { return get(root); } TreeNode get(TreeNode root) { if(root == null) return root; root.left = get(root.left); root.right = get(root.right); if(root.left == null && root.right == null && root.val ==0) { return null; } return root; } }}
转载地址:http://xzyzi.baihongyu.com/