简体   繁体   中英

find successor in AVL tree

there is avl tree with nodes, and each node has only 3 fields:

1.right child

2.left child

3.value(key)

notice that it doesnt have such field "parrent" or "father". my question is: in case we want to know the successor of EVERY node in the tree, and without use any LinkedList or any collection, what is the method to do so?

You could do something like this

// 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);
}

and then call printSuccessors(root, null) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM