I know how to remove children  set the parent's left
or right
to null
. But how can I remove the root?
How can I remove the root?

By introducing a "fakeRoot"?
public class Solution { public List<List<Integer>> findLeaves(TreeNode root) { List<List<Integer>> result = new ArrayList<List<Integer>>(); TreeNode fakeRoot = new TreeNode(0); fakeRoot.right = root; while(fakeRoot.right != null){ List<Integer> current = new ArrayList<Integer>(); dfs(current, fakeRoot); result.add(current); } return result; } private boolean dfs(List<Integer> current, TreeNode node){ if(node == null){ return false; }else{ if(node.left == null && node.right == null){ return true; }else{ if(dfs(current, node.left)){ current.add(node.left.val); node.left = null; } if(dfs(current, node.right)){ current.add(node.right.val); node.right = null; } return false; } } } }

Hi @StefanPochmann, I created a dummy root whose left child is root and right child is NULL.
See my C++ implementation:
https://leetcode.com/discuss/110449/0mscdfssolutionwithdummyroot

I first find the leaf nodes and insert their value in a vector. After this, I make them NULL. As I call the nodes using reference, the root eventually gets deleted.
void find(TreeNode* &root, vector<int> &leaves) { if(root==NULL) return; if(root>left==NULL && root>right==NULL) { leaves.push_back(root>val); root=NULL; return; } find(root>left,leaves); find(root>right,leaves); } vector<vector<int>> findLeaves(TreeNode* root) { vector<vector<int>> all; vector<int> leaves(0); while(root) { find(root,leaves); all.push_back(leaves); leaves.clear(); } return all; }