/*
给定一棵二叉树和其中的一个结点,如何找出中序遍历顺序的下一个结点?
树中的结点除了有两个分别指向左右子结点的指针以外,还有一个指向父结点的指针。
*/
import java.util.*;
public class Class7 {
class TreeLinkNode{
int val;
TreeLinkNode left = null;
TreeLinkNode right = null;
TreeLinkNode parent = null;
TreeLinkNode(int val){
this.val = val;
}
}
public TreeLinkNode findNextNode(TreeLinkNode node){
if(node == null){
System.out.println("所指节点为空!");
return null;
}
if(node.right != null){
node = node.right;
while(node.left != null){
node = node.left;
}
return node;
}
while(node.parent != null){
if(node == node.parent.left){
return node.parent;
}
node = node.parent;
}
return null;
}
public void test() {
TreeLinkNode node1 = new TreeLinkNode(1);
TreeLinkNode node2 = new TreeLinkNode(2);
TreeLinkNode node3 = new TreeLinkNode(3);
TreeLinkNode node4 = new TreeLinkNode(4);
node1.left = node2;
node1.right = node3;
node2.parent = node1;
node3.parent = node1;
node4.left=node1;
node1.parent=node4;
TreeLinkNode nextNodeOf1 = findNextNode(node1);
TreeLinkNode nextNodeOf2 = findNextNode(node2);
TreeLinkNode nextNodeOf3 = findNextNode(node3);
TreeLinkNode nextNodeOf4 = findNextNode(node4);
if(nextNodeOf1!=null)
System.out.println("1结点的下一个结点值为:"+nextNodeOf1.val);
else
System.out.println("1结点无下一结点");
if(nextNodeOf2!=null)
System.out.println("2结点的下一个结点值为:"+nextNodeOf2.val);
else
System.out.println("2结点无下一结点");
if(nextNodeOf3!=null)
System.out.println("3结点的下一个结点值为:"+nextNodeOf3.val);
else
System.out.println("3结点无下一结点");
if(nextNodeOf4!=null)
System.out.println("4结点的下一个结点值为:"+nextNodeOf4.val);
else
System.out.println("4结点无下一结点");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Class7 c = new Class7();
c.test();
}
}