中序遍历 左中右 找前驱结点 分类讨论左孩子
找后继结点,分类讨论右孩子
现在有一种新的二叉树节点类型如下:
public class Node {
public int value;
public Node left;
public Node right;
public Node parent;
public Node(int data) {
this.value = data;
}
}
该结构比普通二叉树节点结构多了一个指向父节点的parent指针。
假设有一 棵Node类型的节点组成的二叉树, 树中每个节点的parent指针都正确地指向自己的父节点,头节点的parent指向null。
只给一个在二叉树中的某个节点 node, 请实现返回node的后继节点的函数。
在二叉树的中序遍历的序列中, node的下一个节点叫作node的后继节点。
一种实现方式(很笨的方法):利用node结点的parent指针,找到头结点,然后利用中序遍历,找到node结点,然后找到它的下一个结点
public static Node findNextNode(Node node){
if(node == null) return null;
Node head = node;
//找到头结点
while(head.parent != null){
head = head.parent;
}
List<Node> nodeList = new ArrayList<>();
inOrder(head, nodeList);
System.out.print("中序遍历结果:");
for(Node n : nodeList){
System.out.print(n.value + " ");
}
System.out.println();
int index = nodeList.indexOf( node );
return nodeList.get(index + 1);
}
public static void inOrder(Node node, List<Node> nodeList){
if(node == null) return;
inOrder(node.left, nodeList);
nodeList.add(node);
inOrder(node.right, nodeList);
}
另外一种实现方式:
可以将该结点分为两种情况,
1.没有右子树,那它是某一个左子树的最后一个结点,然后找到这个左子树的parent即可
找它的parent,直到当前节点是parent的左子树为止
2.有右子树,那它的下一个结点就是它的右子树的最左的结点(若它的右子树没有左子树,那就是右子树本身)
public static Node findNextNode1(Node node){
if(node == null) return null;
//当前节点没有右子树
if(node.right == null) {
Node parentNode = node.parent;
while(parentNode != null && parentNode.left != node){
node = parentNode;
parentNode = node.parent;
}
return parentNode;
} else{
node = node.right;
while(node.left != null){
node = node.left;
}
return node;
}
}