现在有一种新的二叉树节点类型如下:
public class Node {
public int value; public Node left;
public Node right;
public Node parent;
public Node(int data) { this.value = data;
} }
在二 叉树的中序遍历的序列中, node的下一个节点叫作node的后继节点。该结构比普通二叉树节点结构多了一个指向父节点的parent指针。假 设有一 棵Node类型的节点组成的二叉树,树中每个节点的parent指针 都正确地指向 自己的父节点,头节点的parent指向null。只给一个在 二叉树中的某个节点 node,请实现返回node的后继节点的函数。
1 package my_basic.class_4; 2 3 public class Code_03_SuccessorNode { 4 public static class Node { 5 int value; 6 Node parent; 7 Node left; 8 Node right; 9 public Node(int value) { 10 super(); 11 this.value = value; 12 } 13 } 14 15 public static Node getSuccessNode(Node node) { 16 if (node == null) { 17 return null; 18 } 19 if (node.right != null) { 20 return getMostLeft(node.right); 21 }else { 22 Node parent = node.parent; 23 while (parent != null && parent.left != node) { 24 node = parent; 25 parent = node.parent; 26 } 27 return parent; 28 } 29 } 30 31 private static Node getMostLeft(Node head) { 32 if (head.left!=null) { 33 head = head.left; 34 } 35 return head; 36 37 } 38 39 public static void main(String[] args) { 40 Node head = new Node(6); 41 head.parent = null; 42 head.left = new Node(3); 43 head.left.parent = head; 44 head.left.left = new Node(1); 45 head.left.left.parent = head.left; 46 head.left.left.right = new Node(2); 47 head.left.left.right.parent = head.left.left; 48 head.left.right = new Node(4); 49 head.left.right.parent = head.left; 50 head.left.right.right = new Node(5); 51 head.left.right.right.parent = head.left.right; 52 head.right = new Node(9); 53 head.right.parent = head; 54 head.right.left = new Node(8); 55 head.right.left.parent = head.right; 56 head.right.left.left = new Node(7); 57 head.right.left.left.parent = head.right.left; 58 head.right.right = new Node(10); 59 head.right.right.parent = head.right; 60 61 Node test = head.left.left; 62 System.out.println(test.value + " next: " + getSuccessNode(test).value); 63 test = head.left.left.right; 64 System.out.println(test.value + " next: " + getSuccessNode(test).value); 65 test = head.left; 66 System.out.println(test.value + " next: " + getSuccessNode(test).value); 67 test = head.left.right; 68 System.out.println(test.value + " next: " + getSuccessNode(test).value); 69 test = head.left.right.right; 70 System.out.println(test.value + " next: " + getSuccessNode(test).value); 71 test = head; 72 System.out.println(test.value + " next: " + getSuccessNode(test).value); 73 test = head.right.left.left; 74 System.out.println(test.value + " next: " + getSuccessNode(test).value); 75 test = head.right.left; 76 System.out.println(test.value + " next: " + getSuccessNode(test).value); 77 test = head.right; 78 System.out.println(test.value + " next: " + getSuccessNode(test).value); 79 test = head.right.right; // 10's next is null 80 System.out.println(test.value + " next: " + getSuccessNode(test)); 81 } 82 }