1. 二叉树中和为某一值的路径
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
/**
* 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)
* }
*/
/**
* @param {TreeNode} root
* @param {number} target
* @return {number[][]}
*/
var pathSum = function(root, target) {
let result = [];
const getPath = (root, target, total = 0, path = '') => {
if(!root) return;
total += root.val;
path += `${root.val},`;
if(total === target && !root.left && !root.right){
result.push(path.split(',').slice(0, -1));
} else {
getPath(root.left, target, total, path);
getPath(root.right, target, total, path);
}
return;
}
getPath(root, target);
return result;
};
2. 特定深度节点链表
给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {TreeNode} tree
* @return {ListNode[]}
*/
var listOfDepth = function (tree) {
let result = [];
let temp = [];
const toListNode = (tree, index) => {
if (!tree) {
return;
}
if (!result[index]) {
result[index] = new ListNode(tree.val);
temp[index] = result[index];
} else {
temp[index].next = new ListNode(tree.val);
temp[index] = temp[index].next;
}
toListNode(tree.left, index + 1);
toListNode(tree.right, index + 1);
}
toListNode(tree, 0);
return result;
};