题目:
给定一棵二叉树和其中一个节点,如何找出中序遍历序列的下一个节点?树中的节点除了有两个分别指向左、右子节点的指针,还有一个指向父节点的指针。
分析一:
(1)如果一个节点有右子树,那下一个节点就是它右子树的最左子节点。
(2)如果一个节点没有右子树:
(a)如果这个节点是其父节点的左子节点,那下一个节点就是其父节点。
(b)如果这个节点是其父节点的右子节点,就必须沿着指向父节点的指针向上遍历,知道找到是父节点的左子节点的节点, 那下一个节点就是其父节点。
代码一:
package offer.xzs.eighth;
public class NextNode01 {
public static void main(String[] args) {
BinaryTree root = new BinaryTree();
BinaryTree node2 = new BinaryTree();
BinaryTree node3 = new BinaryTree();
BinaryTree node4 = new BinaryTree();
BinaryTree node5 = new BinaryTree();
root.setValue(1);
root.setLeft(node2);
root.setRight(node3);
root.setFather(null);
node2.setFather(root);
node2.setValue(2);
node2.setLeft(node4);
node2.setRight(node5);
node3.setValue(3);
node3.setFather(root);
node3.setRight(null);
node3.setLeft(null);
node4.setValue(4);
node4.setFather(node2);
node4.setRight(null);
node4.setLeft(null);
node5.setValue(5);
node5.setFather(node2);
node5.setRight(null);
node5.setLeft(null);
midOrder(root);
System.out.println();
BinaryTree binaryTree = nextNode(node5);
System.out.println(binaryTree.getValue());
}
public static BinaryTree nextNode(BinaryTree node) {
if (node == null) {
return null;
}
if (node.getRight() != null) {
BinaryTree result = node.getRight();
while (result.getLeft() != null) {
result = result.getLeft();
}
return result;
} else {
while (node.getFather() != null) {
if (node.getFather().getLeft() == node) {
return node.getFather();
}
node = node.getFather();
}
}
return null;
}
public static void midOrder(BinaryTree root) {
if (root == null) {
return;
}
if (root.getLeft() != null) {
midOrder(root.getLeft());
}
System.out.printf("%d\t", root.getValue());
if (root.getRight() != null) {
midOrder(root.getRight());
}
}
}