-
Notifications
You must be signed in to change notification settings - Fork 0
/
allNodesDistanceKinBinaryTree.js
67 lines (64 loc) · 1.68 KB
/
allNodesDistanceKinBinaryTree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} target
* @param {number} k
* @return {number[]}
*/
function downwardDistanceK(node, k, result) {
if(!node || k < 0) {
return;
}
// console.log(node.val + "_" + k)
if(k == 0) {
result.push(node.val);
}
k--;
downwardDistanceK(node.left, k, result);
downwardDistanceK(node.right, k, result)
}
function traversal(node, target, k, result) {
if(!node) {
return -1;
}
// console.log(node.val + "_" + target)
if(node.val == target.val) {
downwardDistanceK(node, k, result);
return 0;
}
let leftDist = traversal(node.left, target, k, result);
if(leftDist != -1) {
if(k == leftDist+1) {
result.push(node.val);
return -1;
} else {
// traversal(node.right, target, k-2, result);
downwardDistanceK(node.right, k-leftDist-2, result);
return leftDist+1;
}
}
let rightDist = traversal(node.right, target, k, result);
if(rightDist != -1) {
if(k == rightDist+1) {
result.push(node.val);
return -1;
} else {
//traversal(node.left, target, k-2, result);
downwardDistanceK(node.left, k-rightDist-2, result);
return rightDist+1;
}
}
return -1;
}
var distanceK = function(root, target, k) {
let result = [];
traversal(root, target, k, result);
return result;
};
//https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/