1. 路径总和 III
给定一个二叉树,它的每个结点都存放着一个整数值。
找出路径和等于给定数值的路径总数。
路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
/**
* 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} targetSum
* @return {number}
*/
var pathSum = function (root, targetSum) {
let result = 0;
const getPath = (root, target, total = 0, path = '') => {
if (!root) return;
total += root.val;
path += `${root.val},`;
if (total === target) {
++result;
}
getPath(root.left, target, total, path);
getPath(root.right, target, total, path);
}
const getRoot = (root, target) => {
if(!root) return;
getPath(root, target);
getRoot(root.left, target);
getRoot(root.right, target);
}
getRoot(root, targetSum);
return result;
};
2. 根据前序和后序遍历构造二叉树
返回与给定的前序和后序遍历匹配的任何二叉树。
pre 和 post 遍历中的值是不同的正整数。
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {number[]} pre
* @param {number[]} post
* @return {TreeNode}
*/
var constructFromPrePost = function(pre, post) {
if(!pre.length > 0){
return null;
}
let temp = pre[0];
let index = post.indexOf(pre[1]);
let node = new TreeNode(temp);
node.left = constructFromPrePost(pre.slice(1, index + 2), post.slice(0, index + 1));
node.right = constructFromPrePost(pre.slice(index + 2), post.slice(index + 1, -1));
return node;
};