Find Leaves of Binary Tree
Description
null
Solution(javascript)
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
// /** 1: parent pointer + BFS
// * @param {TreeNode} root
// * @return {number[][]}
// */
// const findLeaves = function (root) {
// const parent = new Map()
// let current = []
// const visited = new Map()
// const isLeaf = node => !node.left && !node.right
// const aux = (node, parentNode = null) => {
// if (!node) {
// return
// }
// if (isLeaf(node)) {
// current.push(node)
// visited.set(node, true)
// }
// parent.set(node, parentNode)
// aux(node.left, node)
// aux(node.right, node)
// }
// aux(root)
// const result = []
// while (current.length > 0) {
// const next = []
// result.push(current.map(node => node.val))
// for (const node of current) {
// const parentNode = parent.get(node)
// if (parentNode) {
// if (parentNode.left === node) {
// parentNode.left = null
// } else {
// parentNode.right = null
// }
// if (isLeaf(parentNode) && !visited.get(parentNode)) {
// next.push(parentNode)
// visited.set(parentNode, true)
// }
// }
// }
// current = next
// }
// return result
// }
/** 2: 根据 depth 来解决
* @param {TreeNode} root
* @return {number[][]}
*/
const findLeaves = function (root) {
const result = []
const aux = (node) => {
if (!node) {
return -1
}
const depth = 1 + Math.max(aux(node.left), aux(node.right))
result[depth] = result[depth] || []
result[depth].push(node.val)
return depth
}
aux(root)
return result
}