class TreeNode {
constructor(data) {
this
.data = data;
this
.left =
null
;
this
.right =
null
;
}
}
function
countPathsHelper(root, increase, decrease) {
if
(root ===
null
) {
return
{ inc: 0, dec: 0 };
}
const p1 = countPathsHelper(root.left, increase, decrease);
const p2 = countPathsHelper(root.right, increase, decrease);
let inc = 1;
let dec = 1;
if
(root.left !==
null
) {
if
(root.data < root.left.data) {
inc += p1.inc;
}
if
(root.data > root.left.data) {
dec += p1.dec;
}
}
if
(root.right !==
null
) {
if
(root.data < root.right.data) {
inc += p2.inc;
}
if
(root.data > root.right.data) {
dec += p2.dec;
}
}
increase.val += inc;
decrease.val += dec;
return
{ inc, dec };
}
function
countPaths(root) {
const increase = { val: 0 };
const decrease = { val: 0 };
countPathsHelper(root, increase, decrease);
return
{ increase: increase.val, decrease: decrease.val };
}
const root =
new
TreeNode(6);
root.left =
new
TreeNode(4);
root.right =
new
TreeNode(7);
root.left.right =
new
TreeNode(5);
root.right.left =
new
TreeNode(6);
root.right.right =
new
TreeNode(8);
console.log(countPaths(root)[
'increase'
] +
" "
+ countPaths(root)[
'decrease'
]);