[英]find successor in AVL tree
有一個帶有節點的avl樹,每個節點只有3個字段:
1.正確的孩子
2.左孩子
3.值(鍵)
請注意,它沒有這樣的字段“父母”或“父親”。 我的問題是:如果我們想知道樹中每個節點的后繼者,並且不使用任何LinkedList或任何集合,那么這樣做的方法是什么?
你可以做這樣的事情
// Returns the last node in the inorder traversal of tree,
// or prev if tree is null.
Node printSuccessors(Node tree, Node prev) {
if (tree == null) {
return prev;
}
Node lastLeft = printSuccessors(tree.leftChild(), prev);
if (lastLeft != null) {
System.out.println("The successor of " + lastLeft.key()
+ " is " + tree.key());
}
return printSuccessors(tree.rightChild(), tree);
}
然后調用printSuccessors(root, null)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.