Welcome to Subscribe On Youtube
Question
Formatted question description: https://leetcode.ca/all/366.html
Given the root
of a binary tree, collect a tree's nodes as if you were doing this:
- Collect all the leaf nodes.
- Remove all the leaf nodes.
- Repeat until the tree is empty.
Example 1:
Input: root = [1,2,3,4,5] Output: [[4,5,3],[2],[1]] Explanation: [[3,5,4],[2],[1]] and [[3,4,5],[2],[1]] are also considered correct answers since per each level it does not matter the order on which elements are returned.
Example 2:
Input: root = [1] Output: [[1]]
Constraints:
- The number of nodes in the tree is in the range
[1, 100]
. -100 <= Node.val <= 100
Algorithm
Each node is separated from the left child node and the right child node to get two depths,
Since the condition of becoming a leaf node is that the left and right child nodes are empty, we take the larger value of the left and right child nodes plus 1 as the depth value of the current node.
Knowing the depth value, you can add the node value to the correct position in the result.
Code
-
import java.util.ArrayList; import java.util.List; public class Find_Leaves_of_Binary_Tree { public List<List<Integer>> findLeaves(TreeNode root) { List<List<Integer>> result = new ArrayList<List<Integer>>(); helper(result, root); return result; } // traverse the tree bottom-up recursively private int helper(List<List<Integer>> list, TreeNode root) { if (root == null) { return -1; // @note: +1==0, mapping to list index } int left = helper(list, root.left); int right = helper(list, root.right); int currentDepthFromBottom = Math.max(left, right) + 1; // the first time this code is reached is when curr==0, // since the tree is bottom-up processed. if (list.size() <= currentDepthFromBottom) { list.add(new ArrayList<Integer>()); } list.get(currentDepthFromBottom).add(root.val); return currentDepthFromBottom; } } ############ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<List<Integer>> findLeaves(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); TreeNode prev = new TreeNode(0, root, null); while (prev.left != null) { List<Integer> t = new ArrayList<>(); dfs(prev.left, prev, t); res.add(t); } return res; } private void dfs(TreeNode root, TreeNode prev, List<Integer> t) { if (root == null) { return; } if (root.left == null && root.right == null) { t.add(root.val); if (prev.left == root) { prev.left = null; } else { prev.right = null; } } dfs(root.left, root, t); dfs(root.right, root, t); } }
-
// OJ: https://leetcode.com/problems/find-leaves-of-binary-tree/ // Time: O(N) // Space: O(H) class Solution { private: bool dfs(TreeNode *root, vector<int> &v) { if (!root) return true; if (!root->left && !root->right) { v.push_back(root->val); return true; } if (dfs(root->left, v)) root->left = NULL; if (dfs(root->right, v)) root->right = NULL; return false; } vector<int> removeLeaves(TreeNode *root) { vector<int> v; dfs(root, v); return v; } public: vector<vector<int>> findLeaves(TreeNode* root) { if (!root) return {}; vector<vector<int>> ans; while (root->left || root->right) { ans.push_back(removeLeaves(root)); } ans.push_back({ root->val }); return ans; } };
-
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findLeaves(self, root: TreeNode) -> List[List[int]]: def dfs(root, prev, t): if root is None: return if root.left is None and root.right is None: t.append(root.val) if prev.left == root: prev.left = None else: prev.right = None dfs(root.left, root, t) dfs(root.right, root, t) res = [] prev = TreeNode(left=root) while prev.left: t = [] dfs(prev.left, prev, t) res.append(t) return res ############ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None import collections class Solution(object): def findLeaves(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ def helper(p, res): if not p: return 0 left = helper(p.left, res) right = helper(p.right, res) depth = max(left, right) + 1 res[depth].append(p.val) return depth ans = [] res = collections.defaultdict(list) helper(root, res) for i in range(1, len(res) + 1): ans.append(res[i]) return ans
-
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func findLeaves(root *TreeNode) [][]int { prev := &TreeNode{ Val: 0, Left: root, Right: nil, } var res [][]int for prev.Left != nil { var t []int dfs(prev.Left, prev, &t) res = append(res, t) } return res } func dfs(root, prev *TreeNode, t *[]int) { if root == nil { return } if root.Left == nil && root.Right == nil { *t = append(*t, root.Val) if prev.Left == root { prev.Left = nil } else { prev.Right = nil } } dfs(root.Left, root, t) dfs(root.Right, root, t) }