后继节点:在中序遍历中一个节点的下一个节点
二叉树类型如下:
public static class Tree {
private int number;
private Tree leftNode;
private Tree rightNode;
private Tree parent;
public Tree(int number, Tree leftNode, Tree rightNode, Tree parent) {
this.number = number;
this.leftNode = leftNode;
this.rightNode = rightNode;
this.parent = parent;
}
}
如果一个节点有右子树,则其后继节点为其右子树上的最左的节点。
如果一个节点没有右子树:
1、如过该节点为其父节点的左子树,则其后继节点为其父节点
2、如过该节点为其父节点的右子树、则遍历其父节点(包括其父节点的父节点),如果某个节点的左子树是其父节点(包括其父节点的父节点),则其后继节点为该节点。
public class TreeNode {
public static class Node {
private int number;
private Node leftNode;
private Node rightNode;
private Node parent;
public Node(int number, Node leftNode, Node rightNode) {
this.number = number;
this.leftNode = leftNode;
this.rightNode = rightNode;
}
}
public static void creadNodeNode() {
Node Node7 = new Node(7, null, null);
Node Node6 = new Node(6, null, null);
Node Node5 = new Node(5, null, null);
Node Node4 = new Node(4, null, null);
Node Node3 = new Node(3, Node6, Node7);
Node Node2 = new Node(2, Node4, Node5);
Node Node1 = new Node(1, Node2, Node3);
Node1.parent = null;
Node2.parent = Node1;
Node3.parent = Node1;
Node4.parent = Node2;
Node5.parent = Node2;
Node6.parent = Node3;
Node7.parent = Node3;
getNodeNext(Node7);
}
public static void getNodeNext(Node node) {
if (null == node) {
return;
}
if (null != node.rightNode) {
Node nodeLeft = getNodeLeft(node.rightNode);
System.out.println(nodeLeft.number);
} else {
Node p = node.parent;
while (null != p && p.leftNode != node) {
node = p;
p = node.parent;
}
if (null != p) {
System.out.println(p.number);
}
}
}
public static Node getNodeLeft(Node node) {
if (null == node) {
return null;
}
while (null != node.leftNode) {
node = node.leftNode;
}
return node;
}
public static void main(String[] args) {
creadNodeNode();
}
}