366. 寻找二叉树的叶子节点 🔒
366. 寻找二叉树的叶子节点 🔒
🟠 🔖 树
深度优先搜索
二叉树
🔗 力扣
LeetCode
题目
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 1:
1
/ \
2 3
/ \
4 5
Input: [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
题目大意
给你一棵完全二叉树,请按以下要求的顺序收集它的全部节点:
- 依次从左到右,每次收集并删除所有的叶子节点
- 重复如上过程直到整棵树为空
解题思路
二叉树节点的高度的定义是:节点到叶子节点的最长路径(边数),可以发现返回数组其实是按照二叉树的高度来分组的,只需求出每个节点左右子树的最大深度 - 1,即是该节点的高度。
代码
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var findLeaves = function (root) {
if (!root) return [];
let res = [];
const maxDepth = (root) => {
if (!root) return 0;
let depth = Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
res[depth - 1].push(root.val);
return depth;
};
maxDepth(root);
return res;
};