[英]How to find a value in binary expression tree?
給定一棵樹,例如:
我怎樣才能讓我們說找到值3
(不要緊的,其價值3
在樹上,而是一個被發現后,搜索應該得出結論),並可能將其更改為7
或其他一些數字,但在這之后停止遍歷樹? 我在網上找到的所有算法將始終遍歷整棵樹,或者當它們搜索特定值時會遍歷整個BST,此處不適用。 我無法提供代碼示例,因為我不知道從哪里開始這個問題。
class Node {
String value;
Node left, right;
Node(String item) {
value = item;
left = right = null;
}
boolean isLeaf() {
return (left == null) && (right == null);
}
}
首先,您需要一種算法來根據其值查找特定節點。 這可以通過按順序,按順序或按順序遍歷樹來輕松完成(請參閱Wikipedia上的Tree Traversal ,尤其是Depth-first搜索的實現 )。 如果找到該項目,則此算法從遞歸返回:
Node findNode(Node root, String value) {
if (root == null) return null; // no such node
if (value.equals(root.getValue())) return root; // the node itself contains the value
Node n = findNode(root.getLeft(), value); // search left sub-tree
if (n != null) return n; // we've found it in the left sub-tree
return findNode(root.getRight(), value); // search right sub-tree
}
之后,很容易在樹中交換值:
void exchange(Node root, String value, String newValue) {
Node n = findNode(root, value);
n.setValue(newValue);
}
當然,您也可以迭代遍歷樹,但是如果您沒有非常大的樹,則沒有理由不使用更簡單的遞歸方法。
根據您的需要,您將始終必須以順序方式(例如在BFS或DFS中)開始從根元素(我假設您最初可以訪問根)遍歷樹。 由於您的樹不是BST(或節點之間具有某些特殊關系的樹),因此我們無法比在所有節點上進行常規順序搜索更快地搜索特定節點。
樣本BFS偽代碼;
Initialize Queue q;
q.add(root);
while(q is not empty){
Node node = q.pop();
if(Node equal to 3){ // or any value you want
node.val = 7;
return;
}
if(node.left!=null){q.add(node.left);}
if(node.right!=null){q.add(node.right);}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.