问题描述
我的项目中确实需要此功能。即,我有一棵红黑树,我需要编写一个函数以按排序顺序返回所有高于X的值。
示例:
给出以下RBT
function Greater(6)函数应返回[6,8,11,13,13,15,17,22,25,27]
function Greater(11)函数应返回[13、15、17、22、25、27]
有什么建议吗?考虑到我已经找到了节点X的事实,递归是什么?
解决方法
在树上进行有序遍历,当发现大于给定值的值时,将其推入结果数组并返回。
为进行优化而更新:
如果当前节点的值小于目标边界值,则不必检查当前节点的左子树。仅在左子树的值大于等于目标边界值时检查它。
这是带有Javascript代码的有效示例。
/**
* Function to create a tree node with null left and right child
* @param {Number} val
* @return {Node} tree node
* */
function Node(val) {
this.value = val;
this.left = null;
this.right = null;
}
// Constructing the tree
const root = new Node(13);
root.left = new Node(8);
root.left.left = new Node(1);
root.left.left.right = new Node(6);
root.left.right = new Node(11);
root.right = new Node(17);
root.right.left = new Node(15);
root.right.right = new Node(25);
root.right.right.left = new Node(22);
root.right.right.right = new Node(27);
/**
* In-order traversal of a binary tree.
* While processing the current node,we will check and push the value to result array
* @param {Node} node
* @param {Number} contraint value
* @param {Number[]} result array
* @return {Void}
* */
function inorder(node,val,result) {
if (node == null) return;
/**
* We don't have to check the left subtree of the current node if the value
* of the current node is < than target boundary value. Only check left
* subtree if its value is >= target boundary value.
* */
if(node.value >= val) {
inorder(node.left,result);
}
if (node.value > val) {
result.push(node.value);
}
inorder(node.right,result);
}
/**
* @param {Node} root
* @param {Number} value
* @return {Number[]} result
* */
function getValuesAfter(root,value) {
const result = new Array();
inorder(root,value,result);
return result;
}
console.log("Sorted values after 6:");
const result6 = getValuesAfter(root,6);
console.log(result6.join(','));
console.log("Sorted values after 11:");
const result11 = getValuesAfter(root,11);
console.log(result11.join(','));
console.log("Sorted values after 22:");
const result22 = getValuesAfter(root,22);
console.log(result22.join(','));