We are given the head node root
of a binary tree, where additionally every node's value is either a 0 or a 1.html
Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.node
(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:spa
100 nodes
.0
or 1
.
這道題給了咱們一棵二叉樹,說是結點只有0或者1,讓咱們移除全部沒有含有結點1的子樹。題目中也給了一些圖例,不難理解。這道題的難點就在於怎麼看待沒有結點1的子樹,咱們知道子樹也是由一個個結點組成的,須要明確的是一個單獨的葉結點也可算做是子樹,因此值爲0的葉結點必定要移除,就像上面的例子1和3中的幾個葉結點要被移除同樣。對於例子2來講,若是移除了第三行的3個葉結點後,那麼第二行的那個值爲0的結點也變成了葉結點,繼續移除便可,因此與其找值全爲0的子樹,咱們能夠不斷的移除值爲0的葉結點,全都移除後那麼值全爲0的子樹也就都被移除了。code
好,想通了這一點後,咱們看如何來實現。對於玩二叉樹的題,十有八九都是用遞歸,因此咱們應該首先就考慮遞歸的解法,而後再想按什麼順序來遍歷二叉樹呢?層序,先序,中序,仍是後序?根據這道題的特色,咱們要從末尾來一層一層的移除值爲0的葉結點,因此自然時候用後序遍歷。那麼想到這裏,解題思路躍然紙上了吧,咱們首先對結點判空,若是不存在,直接返回空。而後分別對左右子結點調用遞歸函數,此時判斷,若是當前結點是值爲1的葉結點,那麼移除該結點,即返回空,不然返回原結點便可,參見代碼以下:htm
class Solution { public: TreeNode* pruneTree(TreeNode* root) { if (!root) return NULL; root->left = pruneTree(root->left); root->right = pruneTree(root->right); return (!root->left && !root->right && root->val == 0) ? NULL : root; } };
參考資料:blog
https://leetcode.com/problems/binary-tree-pruning/遞歸