| 1 |
/* |
| 2 |
* Licensed to the Apache Software Foundation (ASF) under one |
| 3 |
* or more contributor license agreements. See the NOTICE file |
| 4 |
* distributed with this work for additional information |
| 5 |
* regarding copyright ownership. The ASF licenses this file |
| 6 |
* to you under the Apache License, Version 2.0 (the |
| 7 |
* "License"); you may not use this file except in compliance |
| 8 |
* with the License. You may obtain a copy of the License at |
| 9 |
* |
| 10 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 11 |
* |
| 12 |
* Unless required by applicable law or agreed to in writing, |
| 13 |
* software distributed under the License is distributed on an |
| 14 |
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 |
* KIND, either express or implied. See the License for the |
| 16 |
* specific language governing permissions and limitations |
| 17 |
* under the License. |
| 18 |
*/ |
| 19 |
|
| 20 |
var htrace = htrace || {}; |
| 21 |
|
| 22 |
// |
| 23 |
// Get the height of a tree-- that is, the number of edges on the longest |
| 24 |
// downward path between the root and a leaf |
| 25 |
// |
| 26 |
htrace.treeHeight = function(node, getDescendants) { |
| 27 |
var height = 0; |
| 28 |
var descendants = getDescendants(node); |
| 29 |
for (var i = 0; i < descendants.length; i++) { |
| 30 |
height = Math.max(height, |
| 31 |
1 + htrace.treeHeight(descendants[i], getDescendants)); |
| 32 |
} |
| 33 |
return height; |
| 34 |
}; |
| 35 |
|
| 36 |
// |
| 37 |
// Perform a depth-first, post-order traversal on the tree, invoking the |
| 38 |
// callback on every node with the node and depth as the arguments. |
| 39 |
// |
| 40 |
// Example: |
| 41 |
// 5 |
| 42 |
// / \ |
| 43 |
// 3 4 |
| 44 |
// / \ |
| 45 |
// 1 2 |
| 46 |
// |
| 47 |
htrace.treeTraverseDepthFirstPost = function(node, getDescendants, depth, cb) { |
| 48 |
var descendants = getDescendants(node); |
| 49 |
for (var i = 0; i < descendants.length; i++) { |
| 50 |
htrace.treeTraverseDepthFirstPost(descendants[i], |
| 51 |
getDescendants, depth + 1, cb); |
| 52 |
} |
| 53 |
cb(node, depth); |
| 54 |
}; |
| 55 |
|
| 56 |
// |
| 57 |
// Perform a depth-first, pre-order traversal on the tree, invoking the |
| 58 |
// callback on every node with the node and depth as the arguments. |
| 59 |
// |
| 60 |
// Example: |
| 61 |
// 1 |
| 62 |
// / \ |
| 63 |
// 2 5 |
| 64 |
// / \ |
| 65 |
// 3 4 |
| 66 |
// |
| 67 |
htrace.treeTraverseDepthFirstPre = function(node, getDescendants, depth, cb) { |
| 68 |
cb(node, depth); |
| 69 |
var descendants = getDescendants(node); |
| 70 |
for (var i = 0; i < descendants.length; i++) { |
| 71 |
htrace.treeTraverseDepthFirstPre(descendants[i], |
| 72 |
getDescendants, depth + 1, cb); |
| 73 |
} |
| 74 |
}; |