814-Binary Tree Pruning

kevin聰發表於2018-05-03

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


這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述


Note:

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

問題描述

給定二叉樹的根節點。此二叉樹的每個節點的值為0或者1

對二叉樹進行剪枝, 使得那些所有子樹都為0的節點被剪去
(注意, 子樹包括節點本身)


問題分析

後序遍歷, 判斷當前節點的左右子樹的情況, 若左右子樹為空且當前節點的值為0, 返回null


解法

class Solution {
    public TreeNode pruneTree(TreeNode root) {
        if(root == null)    return null;

        root.left = pruneTree(root.left);
        root.right = pruneTree(root.right);

        if(root.left == null && root.right == null && root.val == 0)    root = null;

        return root;
    }
}