题目描述:
给定一棵二叉树和其中的一个节点,如何找出中序遍历序列的下一个节点?数中的节点除了有两个分别指向 左、右节点的指针,还有一个指向父亲节点的指针。
我们首先看一棵树:
对于求一棵二叉树中序遍历序列中一个节点的下一个节点一般会有3种情况
第一种情况: 节点有右子树,则下一节点就从它的右子树中查找
如图
第二种情况:没有右子节点,而且它还是其父节点的左子节点。
如图:
第三种情况:节点既没有右子树,而且还是父亲节点的右子节点。
如图
相关代码如下:
package test;
class BinaryTreeNode {
public int value;
public BinaryTreeNode leftNode;;
public BinaryTreeNode rightNode;
public BinaryTreeNode parentNode;
public BinaryTreeNode() {
}
public BinaryTreeNode(int value) {
this.value = value;
this.leftNode = null;
this.rightNode = null;
this.parentNode = null;
}
}
public class GetNextTreeNode {
public BinaryTreeNode getNext(BinaryTreeNode pNode) {
BinaryTreeNode currentNode = null;
//情况一:判断是否有右孩子,如果有右孩子
if(pNode.rightNode != null) {
currentNode = pNode.rightNode;
while(currentNode.leftNode != null) {
currentNode = currentNode.leftNode;
}
return currentNode;
}
//情况二:如果是其父节点的左孩子,其父节点就是pNode的下一个节点
else if( pNode.parentNode != null && pNode.parentNode.leftNode == pNode) {
return pNode.parentNode;
}
//情况三:如果pNode节点没有右子树,却其父亲节点,爷爷节点...
//其下一节点就是使其 父亲节点... 处于左子树的最左孩子
else {
currentNode = pNode.parentNode;
while(currentNode.parentNode != null) {//爷爷节点
if(currentNode.parentNode.leftNode == currentNode) {//找出爷爷节点的最左子树
return currentNode.parentNode;
}
currentNode = pNode.parentNode;
}
}
return null;
}
}