LeetCode-Binary Tree Pruning

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Apple_hzc/article/details/83508901

一、Description

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

题目大意:

给定一个二叉树,结点的值为0或1,将这棵树中所有不包含值为1的子树的所有结点包括子树从树中删去,返回原来树的根结点。

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

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


二、Analyzation

通过递归函数,判断左子树和右子树上结点的值和对应的标记(见代码)。对于每个叶子结点,如果值为1,标记为true并返回给对应的父结点,只要一个父结点的左子树或者右子树返回的标记为true,则该父结点保留,否则将该父结点和其子树一起删掉。


三、Accepted code

class Solution {
    public TreeNode pruneTree(TreeNode root) {
        if (root == null) {
            return root;
        }
        help(root);
        return root;
    }
    public boolean help(TreeNode root) {
        boolean left = false, right = false;
        if (root.left != null) {
            left = help(root.left);
            if (!left) {
                root.left = null;
            }
        }
        if (root.right != null) {
            right = help(root.right);
            if (!right) {
                root.right = null;
            }
        }
        if (root.val == 1 || left || right) {
            return true;
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/Apple_hzc/article/details/83508901