[LeetCode] Binary Tree Pruning 二叉樹修剪


 

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

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:

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

 

這道題給了我們一棵二叉樹,說是結點只有0或者1,讓我們移除所有沒有含有結點1的子樹。題目中也給了一些圖例,不難理解。這道題的難點就在於怎么看待沒有結點1的子樹,我們知道子樹也是由一個個結點組成的,需要明確的是一個單獨的葉結點也可算作是子樹,所以值為0的葉結點一定要移除,就像上面的例子1和3中的幾個葉結點要被移除一樣。對於例子2來說,如果移除了第三行的3個葉結點后,那么第二行的那個值為0的結點也變成了葉結點,繼續移除即可,所以與其找值全為0的子樹,我們可以不斷的移除值為0的葉結點,全都移除后那么值全為0的子樹也就都被移除了。

好,想通了這一點后,我們看如何來實現。對於玩二叉樹的題,十有八九都是用遞歸,所以我們應該首先就考慮遞歸的解法,然后再想按什么順序來遍歷二叉樹呢?層序,先序,中序,還是后序?根據這道題的特點,我們要從末尾來一層一層的移除值為0的葉結點,所以天然時候用后序遍歷。那么想到這里,解題思路躍然紙上了吧,我們首先對結點判空,如果不存在,直接返回空。然后分別對左右子結點調用遞歸函數,此時判斷,如果當前結點是值為1的葉結點,那么移除該結點,即返回空,否則返回原結點即可,參見代碼如下:

 

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;
    }
};

 

參考資料:

https://leetcode.com/problems/binary-tree-pruning/

https://leetcode.com/problems/binary-tree-pruning/discuss/122730/C++JavaPython-Self-Explaining-Solution-and-2-lines

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM