Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.
Example:
Input: [1,2,3,4,5]
1
/ \
2 3
/ \
4 5
Output: [[4,5,3],[2],[1]]
Explanation:
1. Removing the leaves [4,5,3]
would result in this tree:
1 / 2
2. Now removing the leaf [2]
would result in this tree:
1
3. Now removing the leaf [1]
would result in the empty tree:
[]
Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.
這道題給了我們一個二叉樹,讓我們返回其每層的葉節點,就像剝洋蔥一樣,將這個二叉樹一層一層剝掉,最后一個剝掉根節點。那么題目中提示說要用DFS來做,思路是這樣的,每一個節點從左子節點和右子節點分開走可以得到兩個深度,由於成為葉節點的條件是左右子節點都為空,所以我們取左右子節點中較大值加1為當前節點的深度值,知道了深度值就可以將節點值加入到結果res中的正確位置了,求深度的方法我們可以參見 Maximum Depth of Binary Tree 中求最大深度的方法,參見代碼如下:
解法一:
class Solution { public: vector<vector<int>> findLeaves(TreeNode* root) { vector<vector<int>> res; helper(root, res); return res; } int helper(TreeNode* root, vector<vector<int>>& res) { if (!root) return -1; int depth = 1 + max(helper(root->left, res), helper(root->right, res)); if (depth >= res.size()) res.resize(depth + 1); res[depth].push_back(root->val); return depth; } };
下面這種DFS方法沒有用計算深度的方法,而是使用了一層層剝離的方法,思路是遍歷二叉樹,找到葉節點,將其賦值為NULL,然后加入leaves數組中,這樣一層層剝洋蔥般的就可以得到最終結果了:
解法二:
class Solution { public: vector<vector<int>> findLeaves(TreeNode* root) { vector<vector<int>> res; while (root) { vector<int> leaves; root = remove(root, leaves); res.push_back(leaves); } return res; } TreeNode* remove(TreeNode* node, vector<int>& leaves) { if (!node) return NULL; if (!node->left && !node->right) { leaves.push_back(node->val); return NULL; } node->left = remove(node->left, leaves); node->right = remove(node->right, leaves); return node; } };
還有一種不用建立新的遞歸函數的方法,就用本身來做遞歸,我們首先判空,然后對左右子結點分別調用遞歸函數,這樣我們suppose左右子結點的所有葉結點已經按順序存好到了二維數組left和right中,現在要做的就是把兩者合並。但是我們現在並不知道左右子樹誰的深度大,我們希望將長度短的二維數組加入到長的里面,那么就來比較下兩者的長度,把長度存到結果res中,把短的存入到t中,然后遍歷短的,按順序都加入到結果res里,好在這道題沒有強行要求每層的葉結點要按照從左到右的順序存入。當左右子樹的葉結點融合完成了之后,當前結點也要新開一層,直接自己組一層,加入結果res中即可,參見代碼如下:
解法三:
class Solution { public: vector<vector<int>> findLeaves(TreeNode* root) { if (!root) return {}; vector<vector<int>> left = findLeaves(root->left), right = findLeaves(root->right); vector<vector<int>> res = (left.size() >= right.size()) ? left : right; vector<vector<int>> t = (left.size() >= right.size()) ? right : left; for (int i = 0; i < t.size(); ++i) { res[i].insert(res[i].begin(), t[i].begin(), t[i].end()); } res.push_back({root->val}); return res; } };
類似題目:
參考資料:
https://leetcode.com/problems/find-leaves-of-binary-tree/