Binary tree: Find a successor of a node

 

Problem Description:

There is a new binary tree node type, the node contains a parent pointer to the parent node (all can be correctly pointed, the parent of the head node points to null),

Only give a node node in the binary tree to realize the function of returning node successor node.

 

Knowledge point: In the sequence of "mid-order traversal" of the binary tree, the next node of node is called "successor node" of node, and the previous node is called "predecessor node" of node.

 

Algorithm implementation:

 

 //Node

class Node {

public int value;
public Node left;
public Node right;
public Node parent;

public Node(int value) {
this.value = value;
}

@NonNull
@Override
public String toString() {
return "Node [value = " + value + "]";
}
}

//方法

public Node getNextNode(Node node) {

if(node == null) {
return node;
}

if(node.right != null) {
return getLeftMost(node.right);
} else {

Node parent = node.parent;
while (parent != null && parent.left != node) {
node = parent;
parent = node.parent;
}
return parent;
}

}

public Node getLeftMost(Node node) {

if(node == null) {
return node;
}
while (node.left != null) {
node = node.left;
}
return node;
}

 

Algorithm analysis:

1. First determine whether the node is empty, and return null directly if it is empty (in the algorithm, "null" judgment is not only a necessary chef judgment operation, but also an important termination condition judgment)

2. If the right node of the current node is not null, the subsequent node must be in the right subtree,

(1)如果此右节点有左子树,则遍历此左子树直到最下层左叶子节点;

(2)如果此右节点无左子树,则当前结点即为要寻找的后继结点。

3.如果当前结点的右节点为null,则后继结点是当前结点的某个父节点(或者当前结点为最后一个节点,不存在后继节点)

(1)找到当前结点的父结点;

(2)当父节点不为空,且当前节点不是父节点的左节点时,需要向上迭代查找;

(3)向上查找时,将找到的父节点转化为子节点,寻找其父节点,并判断是否满足(2)中条件,满足则终止,返回父节点(即为要找的节点);

(4)如果直到父节点为null时,都没有能满足(2)中条件,说明待查找的节点没有后继地点(已经是最后一个节点)。

 

Guess you like

Origin www.cnblogs.com/heibingtai/p/12687654.html