Finding the predecessor nodes for all nodes pre
:
The time complexity of finding the predecessor node for a single node is related to the height of the tree, which is O(log n). Therefore, intuitively, the overall time complexity of finding the predecessor nodes for all nodes in the entire algorithm process would be O(n * log n), but in reality, this process also has a time complexity of O(n).
Take the following tree as an example:
Example Tree
In a binary tree, the predecessor node of any node can be found as follows: starting from the current node, move left once, then continuously move right until the end. The node reached in this way is its predecessor node.
For example, with node 0
, the search process is: first move left to node 1
, then continue moving right, passing through nodes 4
, 8
, 12
, 16
, marking the path (marked as 0, indicating it is the path for finding the predecessor node of node 0
). The same method is applied to other nodes, with corresponding edge markings.
Every left link in the tree is traversed exactly once: for any left link connecting parent node a
and child node b
, it is only traversed when searching for the predecessor node of a
.
As for right links, they are traversed no more than once:
Right links on the direct downward path from the root node along the right child nodes are not traversed, while the rest of the right links are exactly traversed once.
Why right links are traversed no more than once
The text in the top brown box: To find the predecessor of a node, one must first move one step to the left and then as far right as possible.
The text in the left blue box: For the right links on this path, there is no node x that can reach by moving one step to the left and then traversing these right links.
The text in the middle purple box: For the right links on the rest of the tree, there is a node x from which you can move one step to the left and then traverse these right links.
The text in the right green box: Assuming a right link is traversed twice, such as the red link above, there must exist two nodes, x and y, that can first move one step to the left and then reach the same right link. This would mean the red node would have two parents, which contradicts the definition of a binary tree.
Given that a binary tree with n nodes has n-1 edges, the time complexity of this process is O(n).