###### tags: `LeetCode` `Tree` `Recursion` `Medium` # LeetCode #814 [Binary Tree Pruning](https://leetcode.com/problems/binary-tree-pruning/) ### (Medium) 給你二元樹的根結點 root ,此外樹的每個結點的值要嘛是 0 ,要嘛是 1 。 返回移除了所有不包含 1 的子樹的原二元樹。 節點 node 的子樹為 node 本身加上所有 node 的後代。  --- 從葉節點開始處理, 若葉節點(沒有左右子節點)值為0, 則刪除葉節點(因為可以視其為一個沒有1的樹), 處理完葉節點後, 接下來要處理那些本來為葉節點的父節點, 因為刪除葉節點而變成葉節點, 並且其值為0的...以此類推。 --- ``` class Solution { public: TreeNode* pruneTree(TreeNode* root) { if(!root)return nullptr; root->left=root->left?pruneTree(root->left):nullptr; root->right=root->right?pruneTree(root->right):nullptr; if(!root->left&&!root->right&&root->val==0)return nullptr; return root; } }; ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up