1.准备好二叉树结构
public static class Node {
public int value;
public Node left;
public Node right;
public Node parent;
public Node(int data) {
this.value = data;
}
}
2.实现代码
/**
* binary tree find the successor node
* traversal based on preorder
* @return
*/
public static Node getSuccessorNode(Node node) {
// check
if(node == null ){
return null;
}
// the right node no null
if(node.right != null){
//determine whether the right node has a left node
return help(node.right);
} else {
// determine if there is a turning point
while (node.parent != null && node == node.parent.right){
node = node.parent;
}
return node.parent;
}
}
/**
* find successor node help
* @return
*/
private static Node help(Node node) {
while (node.left != null){
node = node.left;
}
return node;
}